Skip to content
Advertisement

Add Javascript to PDF file using iText7 C#

I am trying to add javascript to my PDF file using iText7 library and C#

Currently, here is my code…which is by far not finish yet

public FileResult Download(string id)
    {
        var fileSelect = _context.FileStores.SingleOrDefault(c => c.File_Id == id);
        
        string base64string = Convert.ToBase64String(fileSelect.File_Content, 0, fileSelect.File_Content.Length);


        using (MemoryStream stream = new System.IO.MemoryStream())
        {

            MemoryStream memory = new MemoryStream(fileSelect.File_Content);
            BinaryReader BRreader = new BinaryReader(memory);
            StringBuilder text = new StringBuilder();


            PdfReader reader = new PdfReader(memory);
            //FileStream output = new FileStream(@"Manual.pdf", FileMode.Create);

            PdfDocument Pdfdoc = new PdfDocument(reader);
            Document doc = new Document(Pdfdoc);
            PdfAction action = PdfAction.CreateJavaScript("var rightNow = new Date(); " +
                                                          "var endDate = new Date('May 03, 2021 10:00:00');" +
                                                          "if(rightNow.getTime() > endDate){" +
                                                          "app.alert('This Document has expired, please contact us for a new one');" +
                                                          "this.closeDoc();}");
            reader.Close();

            return File(memory, "application/pdf", "ExportData.pdf");
        }

I want to add this javascript to my PDF and also download the file after it is finished adding the Javascript. Is there anybody that knows how to add Javascript to pdf? thanks

Advertisement

Answer

You can add the Javascript snippet as a document level OpenAction, to be executed when the document is opened:

PdfReader reader = new PdfReader("input.pdf");
PdfWriter writer = new PdfWriter("output.pdf");

PdfDocument Pdfdoc = new PdfDocument(reader, writer);
PdfAction action = PdfAction.CreateJavaScript(
    "var rightNow = new Date(); " +
    "var endDate = new Date('May 03, 2021 10:00:00');" +
    "if(rightNow.getTime() > endDate){" +
    "app.alert('This Document has expired, please contact us for a new one');" +
    "this.closeDoc();}"
);
Pdfdoc.getCatalog().SetOpenAction(action);
Pdfdoc.Close();

Javascript popup

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement