Print PDF file in C# - PrintDocumentWithSettings taking a long time to print

Hello Team,

I am in the process of creating a .net API that prints documents to network printers. The API is working fine in terms of printing the document to network printer but it is taking 35 seconds to send the request to printer. Upon on inspecting I noticed that PrintDocumentWithSettings method is taking 30 seconds to execute. I tried installing the printer driver on the windows 10 server but didn’t help. I also tried adding the network printer to the server but that too didn’t help.
We are using Aspose.Pdf 21.9.0.

Any and every help is appreciated. Please let me know if you need more info.

Thank You,
Manikanta K.

@manikantakondepati

Can you please try using 21.10 version of the API and if issue still persists, please share complete sample code snippet along with sample source PDF file. We will test the scenario in our environment and address it accordingly.

@asad.ali

Hello Ali, Thanks for the response.

I have tried to use 21.10 and 21.10.1 versions of the API but it is still taking 35-40 seconds to print.

Below is the code snip I am using to print a document, to give you a preface of what we are doing, The input to the service will be a formId (to select the overlay/document) and printerQueue (network printer name) and printLineData (the text that goes onto the overlay/document) among other inputs that are not of importance.

public void GenerateReport(SPReportParameters reportParameters)
{
_logger.LogInformation(“Starting WordReporter.GenerateReport”);
var doc = new Document(_templates.Invoke(($“templates:{reportParameters.Template}”)));
_engine.KnownTypes?.Add(reportParameters.GetType());
_engine.KnownTypes?.Add(typeof(DateTime));
_engine.Options = ReportBuildOptions.AllowMissingMembers;

_engine.BuildReport(doc, reportParameters, "doc");
using MemoryStream ms = new MemoryStream();
_logger.LogDebug($"Saving Document to MemoryStream for {reportParameters.Template}");
doc.Save(ms, _saveOptions.Invoke(reportParameters.Format));
var pdfDoc = new Aspose.Pdf.Document(ms);
pdfDoc.Save(ms);
Aspose.Pdf.Page page = pdfDoc.Pages[1];

    _logger.LogDebug($"Adding barcode image to Document {reportParameters?.BarTextLine1}");
    using MemoryStream ms2 = new MemoryStream();
    BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code39Standard, $"*{reportParameters?.BarTextLine1}*");
    generator.Parameters.Barcode.XDimension.Pixels = 1;
    generator.Save(ms2, BarCodeImageFormat.Png);
    Aspose.Pdf.ImageStamp imageStamp = new Aspose.Pdf.ImageStamp(ms2);
    imageStamp.XIndent = 200;   // from left
    imageStamp.YIndent = 30;    // from bottom
    imageStamp.Height = 90;     // 72 points in one inch
    imageStamp.Width = 350;
    imageStamp.Opacity = 1.0;
    imageStamp.Background = true;
    pdfDoc.Pages[1].AddStamp(imageStamp);   // Add stamp to particular page

// TODO - uncomment this to test locally
// pdfDoc.Save(@"D:\temp\overlay.pdf");

_logger.LogDebug($"Printing Document to printer {reportParameters.PrinterQueue}");
// TODO - comment out the below six lines when testing locally where network printer is not configured
using var viewer = new PdfViewer();
viewer.BindPdf(pdfDoc);
viewer.PrintPageDialog = false;
var ps = new System.Drawing.Printing.PrinterSettings();
ps.PrinterName = reportParameters.PrinterQueue;
var pgs = new System.Drawing.Printing.PageSettings(); // This is the line that's taking 35 seconds to execute


// TODO - comment out after debugging
//ps.Copies = reportParameters.NumberCopies;
ps.Copies = 1;
viewer.PrintDocumentWithSettings(ps);

if (viewer.PrintStatus != null)
{
    Exception ex = viewer.PrintStatus as Exception;
    throw ex;
}
else
{
    // no errors found - print job was successful
}

viewer.Close();
_logger.LogInformation("Ending WordReporter.GenerateReport");

}

public class SPReportParameters
{
[JsonProperty(PropertyName = “formId”)]
public string formId { get; set; }

[JsonProperty(PropertyName = "format"), JsonIgnore]
public string Format { get; set; }

[JsonProperty(PropertyName = "stateLogo")]
public string StateLogo { get; set; }

[JsonProperty(PropertyName = "destinationId")]
public string DestinationId { get; set; }

[JsonProperty(PropertyName = "printerQueue")]
public string PrinterQueue { get; set; }

[JsonProperty(PropertyName = "stationId")]
public string stationId { get; set; }

[JsonProperty(PropertyName = "staffId")]
public string staffId { get; set; }

[JsonProperty(PropertyName = "template"), JsonIgnore]
public string Template { get; set; }

//Overlay is the template/document onto which the text is placed 
[JsonProperty(PropertyName = "overlay"), JsonIgnore]
public string Overlay { get; set; }

[JsonProperty(PropertyName = "barTextLine1")]
public string BarTextLine1 { get; set; }

[JsonProperty(PropertyName = "numberCopies")]
public short NumberCopies { get; set; }

[JsonProperty(PropertyName = "totalRows")]
public int? TotalRows { get; set; }

//Text that goes on to the Overlay
[JsonProperty(PropertyName = "printLineData")]
public IEnumerable<DataLine> PrintLineData;

}

@manikantakondepati

It would also be helpful if you could please share a sample PDF document with us. We will include it in our testing and share our feedback with you.

@asad.ali
Test doc.jpg (15.8 KB)

Below is the array of data with formatting, that I am trying to stamp on the attached JPG document.

“printLineData”:

[

{

    "printLine": "   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "           FIRSTNAME  LASTNAME                         000000000000     TESTTES "

},

{

    "printLine": " "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                           "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "           TESTESTESTTESTTE  ADDRESSOVERRIDE                000000000000     NC     "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                   "

},

{

    "printLine": "                                                                "

},

{

    "printLine": "                                                                "

},

{

    "printLine": "                                                                "

},

{

    "printLine": "                                                                "

},

{

    "printLine": "                                                                "

},

{

    "printLine": "                                                                "

},

{

    "printLine": "                                                                "

},

{

    "printLine": "      "

},

{

    "printLine": "                                              "

},

{

    "printLine": "                                              "

},

{

    "printLine": "                                              "

},

{

    "printLine": "                                              "

},

{

    "printLine": "                                              "

},

{

    "printLine": "                                              "

},

{

    "printLine": "                                              "

},

{

    "printLine": "                      "

},

{

    "printLine": "                      "

},

{

    "printLine": "                      "

},

{

    "printLine": "    "

},

{

    "printLine": "                                        "

},

{

    "printLine": "                        "

},

{

    "printLine": "                        "

}                       

]

Please let me know if you have any questions. Thank You…

@manikantakondepati

Please share the PDF document that you have obtained after executing the above part of the entire code. We will use the same document in our environment to test the scenario and address it accordingly.

@asad.ali
overlay.pdf (46.5 KB)
Attached the requested document and below is the content that went on to the document. Please let me know if you need any other information.

 "printLineData":
    [
        {
            "printLine": "                                                                           "
        },
        {
            "printLine": "                                                                           "
        },
        {
            "printLine": "                                                                           "
        },
        {
            "printLine": "                                                                           "
        },
        {
            "printLine": "AAAAAAAAAAAA                                    2021-11-13-14:55:23.228931 "
        },
        {
            "printLine": "                                                                           "
        },
        {
            "printLine": "                                                                           "
        },
        {
            "printLine": "                 AAAAA AAAAAAAA DIVISION OF MOTOR VEHICLES                 "
        },
        {
            "printLine": "                          DRIVER LICENSE SECTION                           "
        },
        {
            "printLine": "                         CONSENT/INFORMATION FORM                          "
        },
        {
            "printLine": "TESTT  TESTTEST                                                            "
        },
        {
            "printLine": "ADD AAAAAAAAAAA RD                                                          "
        },
        {
            "printLine": "AAAAAAAAA NC  12345-7898                                                   "
        },
        {
            "printLine": "Customer No. 000000000000                                                  "
        },
        {
            "printLine": "Dr. Ed. Rep. No.   Dr. Ed.   Sch. Bus                                      "
        },
        {
            "printLine": "Driver please complete the following:            "
        },
        {
            "printLine": ""
        },
        {
            "printLine": "Date of Birth _________ Race ___ Sex ___ County ________                    "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "I hereby authorize Dr./Counselor_____________________________to give any    "
        },
        {
            "printLine": "examination they deem necessary for the purpose of determining my physical  "
        },
        {
            "printLine": "fitness to operate a motor vehicle. I understand this authorization         "
        },
        {
            "printLine": "includes permission for this information to be reviewed by a medical        "
        },
        {
            "printLine": "advisor approved by the division for the purpose of a recommendation to be  "
        },
        {
            "printLine": "rendered to determine my driving needs and abilities.                       "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                           SIGNATURE OF APPLICANT: _______________________  "
        },
        {
            "printLine": "                           PARENT/GUARDIAN IF MINOR:______________________  "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "Telephone No.:Home (___)______________Business(___)________________________ "
        },
        {
            "printLine": "Are you ___Retired____ Disabled______Occupation:___________________________                           "
        },
        {
            "printLine": "What type of vehicle do you drive? Automobile______School Bus______________ "
        },
        {
            "printLine": "Commercial Motor Vehicle_____Other_________________________________________ "
        },
        {
            "printLine": "Does your job require driving? ____________________________________________ "
        },
        {
            "printLine": "___________________________________________________________________________ "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "To Physician                                                                "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "When completing the Medical Report Form, please keep in mind the physical,  "
        },
        {
            "printLine": "mental and emotional requirements necessary for the safe operation of a     "
        },
        {
            "printLine": "motor vehicle, for the patient and public welfare. Please answer all        "
        },
        {
            "printLine": "questions and applicable parts of PP. 2-7, which list thereview of          "
        },
        {
            "printLine": "conditions pertinent to driving. If you circle \"Yes\" for any of these     "
        },
        {
            "printLine": "conditions, you should address all the questions pertaining on the          "
        },
        {
            "printLine": "proceeding pages. You do not need to answer questions on the form for which "
        },
        {
            "printLine": "you circled \"No\". Upon completion of this form please make an overall     "
        },
        {
            "printLine": "statement about your patient's medical condition and its potential effect   "
        },
        {
            "printLine": "on safe driving.                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                           "
        },
        {
            "printLine": "                                                                           "
        },
        {
            "printLine": "                                  -1-                                       "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        },
        {
            "printLine": "                                                                            "
        }
    ]

@manikantakondepati

We tested the scenario in local environment and could not reproduce the issue of delay at our side. Furthermore, we noticed that you are not using PageSettings() anywhere in your code snippet. If you are not using it in your original scenario, you do not need to initialize it as it is taking long time. In case you need to use it, please try to initialize it with default settings like below:

System.Drawing.Printing.PageSettings pgs = ps.DefaultPageSettings;

@asad.ali
Hello Ali, As per your suggestion, I have removed the below piece of code, which I was not using.
var pgs = new System.Drawing.Printing.PageSettings();
But it is still taking the same time to print the document.
Like I have mentioned in my initial post, viewer.PrintDocumentWithSettings(ps); is taking a long time to complete.
Is there a way for me to do work with you so that maybe we can have a screen share session to debug the code. Please suggest.

Thank You,
Mani K.

@manikantakondepati

We apologize that we cannot work with you while sharing the screen. However, you can please record a short video or GIF to share with us so that we can observe the delay at your end and perform investigation accordingly.

@asad.ali

The code I have:
_logger.LogDebug(“Before PrintDocumentWithSettings”);
viewer.PrintDocumentWithSettings(ps);
_logger.LogDebug(“After PrintDocumentWithSettings”);
Logs:

2021-11-29T14:39:38.3195262-05:00 [DBG] (SilentPrinting.Managers.WordReporter) Before PrintDocumentWithSettings
2021-11-29T14:40:19.7017643-05:00 [DBG] (SilentPrinting.Managers.WordReporter) After PrintDocumentWithSettings

When printing to network printer, if you observe the time difference between log line 1 and 2, there is a gap of approximately 40 seconds. That is the time its taking to execute PrintDocumentWithSettings function when printing to network printer.

When printing to local printer, which is connected to my PC via USB, its taking just 7 seconds.

Hope this helps, please let me know if you have any questions. Thank You…

@manikantakondepati

We need to further investigate the issue in order to determine the cause behind this delay. For this purpose, we have logged an investigation ticket as PDFNET-50987 in our issue tracking system. We will further look into its details and keep you posted with the status of its resolution. Please be patient and spare us some time.

We are sorry for the inconvenience.

@asad.ali Thanks for the update, hoping for a quick resolution as the project I am working on is time sensitive to my organization. Appreciate all your help.

@asad.ali
I noticed in the code I originally provided you, I had mentioned that
“var pgs = new System.Drawing.Printing.PageSettings(); // This is the line that’s taking 35 seconds to execute”

Which is misleading, So want to reiterate again that the one that’s taking a long time to execute is viewer.PrintDocumentWithSettings(ps);

@manikantakondepati

We have updated the ticket information accordingly and will surely investigate it from the perspective of our discussion. Please note that we will analyze and resolved the ticket on a first come first serve basis and let you know as soon as the ticket is resolved. Please spare us some time.

@asad.ali
Any update on the issue, please let us know if you need more information. Thank You…

@manikantakondepati

We are afraid that the ticket has not been yet resolved. As shared earlier, it will be analyzed and resolved on a first come first serve basis and its resolution time depends upon its complexity and number of issues logged prior to it. However, we will certainly let you know in case we have some updates to share or require any additional information from your side in this regard. We greatly appreciate your patience.

We apologize for the inconvenience.

@asad.ali
Network capture.zip (296 Bytes)

I have attached a file which has the link to a drive where you can find network capture between the app server and the print server. Please see if that helps.

@manikantakondepati

We have logged the provided information along with the ticket and will surely investigate the task from this perspective. Please note that it seems like the issue is not mainly related to the API but printing over network. Usually, the printing on networked printers are slow due to multiple reasons. For example, please check the linked article where some tips are shared in order to improve the printing speed. Furthermore, we will share updates with you as soon as the ticket is completely investigated.

@asad.ali
Thanks for the update, we looked into the article and those three conditions mentioned in the article doesn’t apply to us, at this point I would like to know what “PrintDocumentWithSettings” is doing so that may be we can also do some research on our end.