Generate a PDF that automatically prints

Method 1: Using embedded javascript inside your PDF files
You can try creating an iText PDFAction object with a javascript call this.print(false) (you can use new PdfAction(PdfAction.PRINTDIALOG) for this), and associate it with the OpenAction event of your pdf file.

The code in iText Java should look like this:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("file.pdf"));
...
PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
writer.setOpenAction(action);
...

It should not be too diferent in C#.

As a side note, this is also possible with Amyuni PDF Creator .Net by setting the attribute “AutoPrint” to TRUE in the document class (usual disclaimer applies).

acPDFCreatorLib.Initialize();
acPDFCreatorLib.SetLicenseKey("Amyuni Tech.", "07EFCDA00...BC4FB9CFD");
Amyuni.PDFCreator.IacDocument document = pdfCreator1.Document;

// Open a PDF document from file
System.IO.FileStream file1 = new System.IO.FileStream("test_input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read);

IacDocument document = new IacDocument(null);

if (document.Open(file1, ""))
{
    //Set AutoPrint
    document.Attribute("AutoPrint").Value = true;

    //Save the document
    System.IO.FileStream file2 = new System.IO.FileStream("test_output.pdf", System.IO.FileMode.Create, System.IO.FileAccess.Write);
    document.Save(file2, Amyuni.PDFCreator.IacFileSaveOption.acFileSaveView);
}

// Disposing the document before closing the stream clears out any data structures used by the Document object
document.Dispose();

file1.Close();

// terminate library to free resources
acPDFCreatorLib.Terminate();

This approach requires the PDF file to be opened in a reader that will take care of printing, and it has the drawback that if the file is saved locally, every time the file is opened later on it will show the print dialog.

Method 2: Using javascript from the browser to communicate with the reader that shows the file.
I found this other approach in this SO question that might worth trying:

<html>
<script language="javascript">
timerID = setTimeout("exPDF.print();", 1000);
</script>
<body>
<object id="exPDF" type="application/pdf" data="111.pdf" width="100%" height="500"/>
</body>
</html>

The idea is to use javascript in the browser to instruct the PDF reader to print the file. This approach will work on PDF files embedded in a HTML page.

Leave a Comment