简体   繁体   中英

Add javascript to pdf file using iTextSharp

I want to embed a javascript snippet inside of a pdf file so that it will immediately print when it's opened from a browser window. To try and achieve this I'm following this example here.

I have created a helper class that has a static method to handle this task. I already have the pdf file path string ready to pass into the method. What I don't understand is how the output stream portion of this works. I would like the updated pdf to be saved to my servers hard drive. I do not want to stream it back to my browser. Any guidance would be greatly appreciated.

public class PdfHelper
{
    public static void AddPrintFunction(string pdfPath, Stream outputStream)
    {
        PdfReader reader = new PdfReader(pdfPath);
        int pageCount = reader.NumberOfPages;
        Rectangle pageSize = reader.GetPageSize(1);

        // Set up Writer 
        PdfDocument document = new PdfDocument();

        PdfWriter writer = PdfWriter.GetInstance(document, outputStream);

        document.Open();

        //Copy each page 
        PdfContentByte content = writer.DirectContent;

        for (int i = 0; i < pageCount; i++)
        {
            document.NewPage();
            // page numbers are one based 
            PdfImportedPage page = writer.GetImportedPage(reader, i + 1);
            // x and y correspond to position on the page 
            content.AddTemplate(page, 0, 0);
        }

        // Inert Javascript to print the document after a fraction of a second to allow time to become visible.
        string jsText = "var res = app.setTimeOut(‘var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);’, 200);";

        //string jsTextNoWait = “var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);”;
        PdfAction js = PdfAction.JavaScript(jsText, writer);
        writer.AddJavaScript(js);

        document.Close();

    }
} 

For how to accomplish this task, please take a look at this and this SO posts.

Basically you should have something like this:

var pdfLocalFilePath = Server.MapPath("~/sourceFile.pdf");
var outputLocalFilePath = Server.MapPath("~/outputFile.pdf");
using (var outputStream = new FileStream(outputLocalFilePath, FileMode.CreateNew))
{
    AddPrintFunction(pdfLocalFilePath, outputStream);
    outputStream.Flush();
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM