Create New PDF and print using .NET PDF

I have code to create a PDF. It works on my local printer. When I put it in another environment, this created pdf does not print. I have print an existing document to both trays of the printer, so I know it is not the tray definition. I also logged the source name of the paper trays before the print is to occur, and it logs as expected. I even saved the document as a stream to make sure it didn’t need to be saved in the remote environment first. Would love input as to what this could be, this is the code:

public Document CoverSheetPrintJob(PrintingJobSettings pjs, Core.Models.PrintQueue pq)
    {
        // The path to the documents directory.
        Document docPdf = new Document();

        // Create TextBuilder object
        Page pdfPage = docPdf.Pages.Insert(1);
        TextBuilder textBuilder = new TextBuilder(pdfPage);

        String dt = String.Format("{0:d} {0:t}", DateTime.Now);
        TextFragment userName = CreateText(30, 600, pq.username);

        // Append the text fragment to the PDF page
        textBuilder.AppendText(userName);

        // Create TextBuilder object
        pdfPage = docPdf.Pages[1];
        textBuilder = new TextBuilder(pdfPage);
        var claimNumber = pq.mccaClaimNumber != null ? pq.mccaClaimNumber.Value : 0;
        TextFragment theClaimNumber = CreateText(30, 550, claimNumber.ToString() );

        textBuilder.AppendText(theClaimNumber);
        
        // Create TextBuilder object
        pdfPage = docPdf.Pages[1];
        textBuilder = new TextBuilder(pdfPage);
        TextFragment dateTime = CreateText(30, 500, dt);
        textBuilder.AppendText(dateTime);
        
        PdfViewer viewer = new PdfViewer();
        viewer.BindPdf(docPdf);
        viewer.PrinterJobName = System.IO.Path.GetFileName(pq.documentURL);
        viewer.Resolution = 110;
        // Set attributes for printing
        viewer.AutoResize = true; // Print the file with adjusted size
        viewer.AutoRotate = false; // Print the file with adjusted rotation
        viewer.PrintPageDialog = false; // Do not produce the page number dialog when printing
        viewer.RenderingOptions.UseNewImagingEngine = true;

        // Create objects for printer and page settings and PrintDocument
        System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
        System.Drawing.Printing.PageSettings pgs = new System.Drawing.Printing.PageSettings();
        ps.PrinterName = _printerName;
        pgs.PaperSize = new System.Drawing.Printing.PaperSize("A4", 827, 1169);
        pgs.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);

        System.Drawing.Printing.PrintDocument prtDoc = new System.Drawing.Printing.PrintDocument();
        prtDoc.PrinterSettings.PrinterName = ps.PrinterName;
        if (prtDoc.PrinterSettings.PaperSources.Count > 1)
        {
            pgs.PaperSource = prtDoc.PrinterSettings.PaperSources[_documentTrayIndex];
            _logger.Log(LogLevel.Information, null, "Document Paper Source Name (used by coversheet) is " + pgs.PaperSource.SourceName);
        }
        else
        {
            pgs.PaperSource = prtDoc.PrinterSettings.PaperSources[_coverSheetTrayIndex];
            _logger.Log(LogLevel.Information, null, "Cover Sheet Paper Source Name is " + pgs.PaperSource.SourceName);
        }

        return docPdf;

    }

Thanks,
John Quinn

@jwquinn

Thank you for contacting support.

Would you please elaborate the other environment, is this a different operating system or a network printer, etc.? Moreover, can you please try to print a file without using Aspose.PDF but only .NET classes, for example, the below code snippet may be modified a little as per your requirements. This can help us narrow down the reason and investigate further.

printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
System.Drawing.Printing.PrinterSettings objPrinterSettings = new System.Drawing.Printing.PrinterSettings();
objPrinterSettings.PrinterName = "Brother HL-4150CDN series Printer";
objPrinterSettings.DefaultPageSettings.PaperSource= objPrinterSettings.PaperSources[2];
pd.PrinterSettings = objPrinterSettings;
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.Print ();
objPrinterSettings.DefaultPageSettings.PaperSource = objPrinterSettings.PaperSources[5];
pd.PrinterSettings = objPrinterSettings;
pd.Print();

In case the issue persists with API then please share a sample application containing SSCCE code so that we may proceed further.

Okay, so I have 2 different scenarios to talk about now. I will start with my original problem and relay the specifics. The .NET version on all servers is 4.7.2.

Locally I print from a WIndows Service running on a VM. The VM is a Windows Server 2016 Standard server. This server sends my cover sheet to the correct paper tray local. The local printer is an Dell Color MFP S2825cdn PCL6 and the cover sheet paper source is from a manual feed print tray. Works great.

Remotely, I print from a Windows Service running on a VM. The VM is a Windows Server 2012 Standard server. This server never prints my cover sheet at all, I even tried sending it to the same paper tray as the document, but it is as if I never tried to print this at all. The remote printer is a Xerox Versalink B610. Cover sheet never shows up, no matter which paper tray I point it at, but the document prints out just fine.

Both servers send my pdf document to the correct paper tray.

Here is the code to print the cover sheet using Aspose, I think there are only 3 places you need to edit, and then remove the parameter from the method to get this to work after taking out the logging statements (which work by the way, so I know it gets there and shows the trays that are available,etc):

    public void CoverSheetPrintJob(Core.Models.PrintQueue pq)
    {
        // The path to the documents directory.
        Document docPdf = new Document();
        PrintingJobSettings pjs = new PrintingJobSettings();
        pjs.FromPage = 1;
        pjs.ToPage = 1;
        // Create TextBuilder object
        Page pdfPage = docPdf.Pages.Insert(1);
        TextBuilder textBuilder = new TextBuilder(pdfPage);

        String dt = String.Format("{0:d} {0:t}", DateTime.Now);
        TextFragment userName = CreateText(30, 600, pq.username);  //Just replace pq.username with a string value of your choice to get this to work.

        // Append the text fragment to the PDF page
        textBuilder.AppendText(userName);

        // Create TextBuilder object
        pdfPage = docPdf.Pages[1];
        textBuilder = new TextBuilder(pdfPage);
        var claimNumber = pq.mccaClaimNumber != null ? pq.mccaClaimNumber.Value : 0;
        TextFragment theClaimNumber = CreateText(30, 550, claimNumber.ToString()); //Again, just replace claimNumber with an 1-8 digit integer and this should work fine.

        textBuilder.AppendText(theClaimNumber);

        // Create TextBuilder object
        pdfPage = docPdf.Pages[1];
        textBuilder = new TextBuilder(pdfPage);
        TextFragment dateTime = CreateText(30, 500, dt);
        textBuilder.AppendText(dateTime);

        var pdfPath = _baseFileSharePath;
        MemoryStream streamPdf = new MemoryStream();
        docPdf.Save(streamPdf);
        
        // Create objects for printer and page settings and PrintDocument
        System.Drawing.Printing.PrintDocument prtDoc = new System.Drawing.Printing.PrintDocument();
        prtDoc.PrinterSettings.PrinterName = _printerName;

        var jsonPrintSettings = JsonConvert.SerializeObject(prtDoc.PrinterSettings.PaperSources, Formatting.Indented);
        _logger.Log(LogLevel.Information, null, String.Format("Paper Source has printer settings in CoverSheet:\n {0} ", jsonPrintSettings));



        using (var theViewer = new Aspose.Pdf.Facades.PdfViewer())
        {
            // Print document using printer and page settings
            PageSettings pgs = new PageSettings();
            PrinterSettings ps = new PrinterSettings();

            ps.PrintRange = PrintRange.SomePages;
            ps.FromPage = 1;
            ps.ToPage = 1;
            ps.PrinterName = _printerName;
            pgs.PaperSize = new System.Drawing.Printing.PaperSize("A4", 827, 1169);
            pgs.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);
            pgs.PaperSource = prtDoc.PrinterSettings.PaperSources[PrintDocuments._coverSheetTrayIndex];

            _logger.Log(LogLevel.Information, null, "Paper Tray Source Name is: " + pgs.PaperSource.SourceName);
            _logger.Log(LogLevel.Information, null, "Cover Sheet Tray Index is: " + PrintDocuments._coverSheetTrayIndex);

            theViewer.BindPdf(docPdf);
            theViewer.AutoResize = true;
            theViewer.AutoRotate = true;
            theViewer.PrintPageDialog = false;
            theViewer.RenderingOptions.UseNewImagingEngine = true;
            //theViewer.PdfQueryPageSettings += PdfvOnPdfQueryPageSettings;
            theViewer.PrintDocumentWithSettings(pgs, ps);

            if (theViewer.PrintStatus != null)

            {
                Exception ex = (Exception)theViewer.PrintStatus;
                var success = false;
                WriteLog(string.Format("After PrintDocumentWithSettings(): (PrintQueue) Cover Sheet: Aspose PDF print document encountered exception: {0} : inner exception: {1},", ex.Message, ex.InnerException), ex);

            }
            else
            {
                var success = true;
            }
            theViewer.Close();
        }

        streamPdf.Close();
    }

Okay, that is my main scenario where I am using Aspose to print the cover sheet. I did not show the code that submits the document to the printer, but it looks very much like this code, except that it is using an existing document, not a document that is created on the fly.

Now, I also tried my hand at the code you sent me. Locally, I cannot get this to send to the correct tray, it always goes to the tray the document should go to instead of the manual paper tray. However, on the remote server, this seems to be working just fine. Almost like the problem reversed itself, except that the remote server doesn’t print the Aspose cover sheet anywhere at all, while the local server does print out the .NET cover sheet, just to the wrong paper tray for some reason. My client has paid support, so if that helps us solve this situation faster, that would be great, just let me know what you need from me.

Thanks,
John Quinn

PS, here’s the code to print the .NET cover sheet (anywhere you see doc, just replace it with a string value of some type):

    public void CoverSheetNetPrintJob(Core.Models.PrintQueue pq)

    {
        var printFont = new System.Drawing.Font("Arial", 20);
        PrintDocument pd = new PrintDocument();
        System.Drawing.Printing.PrinterSettings objPrinterSettings = new System.Drawing.Printing.PrinterSettings();
        objPrinterSettings.PrinterName = _printerName;

        var printerSettings = new PrinterSettings();
        printerSettings.PrinterName = _printerName;
        var jsonPrintSettings = JsonConvert.SerializeObject(printerSettings.PaperSources, Formatting.Indented);
        _logger.Log(LogLevel.Information, null, String.Format("Paper Source has printer settings in CoverSheetNet:\n {0} ", jsonPrintSettings));

        pd.PrinterSettings = printerSettings;
        pd.PrinterSettings.DefaultPageSettings.PaperSource = printerSettings.PaperSources[_coverSheetTrayIndex];
        _logger.Log(LogLevel.Information, null, String.Format(".NET PaperSource Name is: {0}", pd.PrinterSettings.DefaultPageSettings.PaperSource.SourceName));

        pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
        pd.Print();
        _logger.Log(LogLevel.Information, null, String.Format(".NET PaperSource Name is: {0}", objPrinterSettings.DefaultPageSettings.PaperSource.SourceName));

    }
    // The PrintPage event is raised for each page to be printed.
    private void pd_PrintPage(object sender, PrintPageEventArgs ev)
    {
        var printFont = new System.Drawing.Font("Arial", 20);
        float linesPerPage = 0;
        float yPos = 0;
        float leftMargin = ev.MarginBounds.Left;
        float topMargin = ev.MarginBounds.Top;

        // Calculate the number of lines per page.
        linesPerPage = ev.MarginBounds.Height /
           printFont.GetHeight(ev.Graphics);

        // Print each line of the file.
        yPos = topMargin + (printFont.GetHeight(ev.Graphics));
        ev.Graphics.DrawString(doc.username, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());


        yPos = yPos + (printFont.GetHeight(ev.Graphics));

        var claimNumber = doc.mccaClaimNumber != null ? doc.mccaClaimNumber.Value : 0;
        ev.Graphics.DrawString(claimNumber.ToString(), printFont, Brushes.Black, leftMargin, yPos, new StringFormat());


        yPos = yPos + (printFont.GetHeight(ev.Graphics));
        ev.Graphics.DrawString(DateTime.Now.ToShortDateString(), printFont, Brushes.Black, leftMargin, yPos, new StringFormat());


    }

@jwquinn

Thank you for elaborating it further.

We are looking into it and will get back to you shortly.

@jwquinn

We have logged a ticket with ID PDFNET-46908 in our issue management system for detailed investigations and will let you know once any update will be available in this regard.

Thanks for the update. What kind of time frame are we looking at for this would you guess?

@jwquinn

We will try to share our findings with you in couple of weeks. Please spare us some time.

@jwquinn

We were not able to reproduce the issue (in part because we can’t recreate the your environment. We’ve run your code in the Windows Server 2012 R2 VM, but had to use virtual printers as we have no access to a hardware one).

We’re not sure if we can get any additional information on this task from you (is it still relevant at all after years of inactivity?), but it seems to us more as some configuration issue in the your environment. For some printers actions like setting a custom paper size may lead to printing errors if the printer doesn’t support requested settings. Is it possible to get any print job logs from the you to check them for printer-specific errors?

You told us that you were able to print another document without any problem - could we get the exact code you used to print it? (If mistaken, the code snippet for the successful document wasn’t provided).

Since you weren’t able to print the cover sheet correctly even using the intrinsic .NET printing mechanism (System.Drawing.Printing.PrintDocument), it adds to our suspicion that the problem probably isn’t related to our library, but is some printer misconfiguration or the case of incompatible settings send to the printer.