private static byte[] Merge(Collection <byte[]> pdfCollection, Document document, string script)
        {
            if (pdfCollection == null)
            {
                throw new ArgumentNullException("pdfCollection");
            }

            // get a list of readers for the collection of bytes passed in
            var readers    = pdfCollection.Where(b => b != null).Select(b => new PdfReader(b)).ToList();
            var totalPages = readers.Sum(r => r.NumberOfPages);

            byte[] mergedPdf;
            using (var stream = new MemoryStream())
            {
                var writer = new PdfSmartCopy(document, stream);
                document.Open();

                var currentPage = 1;
                readers.ForEach(r => { currentPage = Append(writer, r, document, currentPage, totalPages); });

                if (!string.IsNullOrEmpty(script))
                {
                    var action = PdfAction.JavaScript(script, writer);
                    writer.AddJavaScript(action);
                }

                document.Close();
                stream.Flush();
                mergedPdf = stream.ToArray();
            }

            return(mergedPdf);
        }
Example #2
0
        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();
        }
Example #3
0
// ---------------------------------------------------------------------------    
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     */
    public byte[] ManipulatePdf(byte[] src)  {
      // create a reader
      PdfReader reader = new PdfReader(src);
      using (MemoryStream ms = new MemoryStream()) {
        // create a stamper
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          // Add an open action
          PdfWriter writer = stamper.Writer;
          PdfAction action = PdfAction.JavaScript(
            Utilities.ReadFileToString(
              Path.Combine(Utility.ResourceJavaScript, "post_from_html.js")
            ), 
            writer
          );
          writer.SetOpenAction(action);
          // create a submit button that posts data to the HTML page
          PushbuttonField button1 = new PushbuttonField(
            stamper.Writer, new Rectangle(90, 660, 160, 690), "post"
          );
          button1.Text = "POST TO HTML";
          button1.BackgroundColor = new GrayColor(0.7f);
          button1.Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
          PdfFormField submit1 = button1.Field;
          submit1.Action = PdfAction.JavaScript(
            Utilities.ReadFileToString(Path.Combine(
              Utility.ResourceJavaScript, "post_to_html.js"
            )), 
            writer
          );
          // add the button
          stamper.AddAnnotation(submit1, 1);
        }
        return ms.ToArray();
      } 
    }  
Example #4
0
        public Chap1106()
        {
            Console.WriteLine("Chapter 11 example 6: javascript");

            // step 1: creation of a document-object
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);

            try
            {
                // step 2:
                // we create a writer that listens to the document
                // and directs a PDF-stream to a file
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap1106.pdf", FileMode.Create));

                // step 3: we open the document
                document.Open();

                // step 4: we add content
                PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
                writer.AddJavaScript(jAction);
                document.Add(new Paragraph("Page 1"));
            }
            catch (Exception de)
            {
                Console.Error.WriteLine(de.Message);
                Console.Error.WriteLine(de.StackTrace);
            }

            // step 5: we close the document
            document.Close();
        }
Example #5
0
        /// <summary>
        ///     Adds the script to PDF.
        /// </summary>
        /// <param name="pdfStamper">The PDF stamper.</param>
        /// TODO Edit XML Comment Template for AddScriptToPdf
        private void AddScriptToPdf(PdfStamper pdfStamper)
        {
            var pdfAction = PdfAction.JavaScript(Script.Text, pdfStamper.Writer);

            pdfStamper.Writer.SetAdditionalAction(
                ActionTypeMapping[Script.Timing],
                pdfAction);
        }
        /* will print A4 Landscape 11.69 x 8.27 */
        protected void print_A4_landscape()
        {
            Warning[] warnings;
            string[]  streamids;
            string    mimeType;
            string    encoding;
            string    extension;

            string dtnow = DateTime.Now.ToString("ddMMMyyyy_hh_mm_ss");

            byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType,
                                                            out encoding, out extension, out streamids, out warnings);

            string fileOUT = HttpContext.Current.Server.MapPath(@"\Areas\ManagementReports\Reports\TempReport\" + "output_" + dtnow + "_" + rtype.ToString() + ".pdf");

            FileStream fs = new FileStream(fileOUT,
                                           FileMode.Create);

            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
            Document document = new Document(PageSize.A4.Rotate());
            //Open existing PDF
            PdfReader reader = new PdfReader(fileOUT);
            //Getting a instance of new PDF writer
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(
                                                         HttpContext.Current.Server.MapPath(@"\Areas\ManagementReports\Reports\TempReport\" + "print_" + dtnow + "_" + rtype.ToString() + ".pdf"), FileMode.Create));

            document.Open();
            PdfContentByte cb = writer.DirectContent;

            int       i     = 0;
            int       p     = 0;
            int       n     = reader.NumberOfPages;
            Rectangle psize = reader.GetPageSize(1);

            float width  = psize.Width;
            float height = psize.Height;

            //Add Page to new document
            while (i < n)
            {
                document.NewPage();
                p++;
                i++;

                PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page1, 0, 0);
            }

            //Attach javascript to the document
            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);

            writer.AddJavaScript(jAction);
            document.Close();

            //Attach pdf to the iframe
            //frmPrint.Attributes["src"] = @"\Areas\ManagementReports\Reports\TempReport\" + "print_" + dtnow + "_" + rtype.ToString() + ".pdf";
        }
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            Warning[] warnings;
            string[]  streamids;
            string    mimeType;
            string    encoding;
            string    extension;

            byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType,
                                                            out encoding, out extension, out streamids, out warnings);

            FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"),
                                           FileMode.Create);

            fs.Write(bytes, 0, bytes.Length);
            fs.Close();

            //Open existing PDF
            Document  document = new Document(PageSize.LETTER);
            PdfReader reader   = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf"));
            //Getting a instance of new PDF writer
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(
                                                         HttpContext.Current.Server.MapPath("Print.pdf"), FileMode.Create));

            document.Open();
            PdfContentByte cb = writer.DirectContent;

            int       i     = 0;
            int       p     = 0;
            int       n     = reader.NumberOfPages;
            Rectangle psize = reader.GetPageSize(1);

            float width  = psize.Width;
            float height = psize.Height;

            //Add Page to new document
            while (i < n)
            {
                document.NewPage();
                p++;
                i++;

                PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page1, 0, 0);
            }

            //Attach javascript to the document
            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);

            writer.AddJavaScript(jAction);
            document.Close();

            //Attach pdf to the iframe
            frmPrint.Attributes["src"] = "Print.pdf";
        }
Example #8
0
        private void addAttachmentsOutline()
        {
            if (_attachmentsCount <= 0)
            {
                return;
            }
            var action      = PdfAction.JavaScript("app.execMenuItem('ShowHideFileAttachment');", _writer);
            var rootOutline = _writer.DirectContent.RootOutline;

            new PdfOutline(rootOutline, action, AttachmentsBookmarkLabel + " " + _attachmentsCount);
        }
Example #9
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            // Create a reader for the original document
            PdfReader reader = new PdfReader(src);
            // Create a reader for the advertisement resource
            PdfReader ad = new PdfReader(RESOURCE);

            using (MemoryStream ms = new MemoryStream())
            {
                // Create a stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Create the advertisement annotation for the menubar
                    Rectangle       rect   = new Rectangle(400, 772, 545, 792);
                    PushbuttonField button = new PushbuttonField(
                        stamper.Writer, rect, "click"
                        );
                    button.BackgroundColor = BaseColor.RED;
                    button.BorderColor     = BaseColor.RED;
                    button.FontSize        = 10;
                    button.Text            = "Close this advertisement";
                    button.Image           = Image.GetInstance(
                        Path.Combine(Utility.ResourceImage, IMAGE)
                        );
                    button.Layout = PushbuttonField.LAYOUT_LABEL_LEFT_ICON_RIGHT;
                    button.IconHorizontalAdjustment = 1;
                    PdfFormField menubar = button.Field;
                    String       js      = "var f1 = getField('click'); f1.display = display.hidden;"
                                           + "var f2 = getField('advertisement'); f2.display = display.hidden;"
                    ;
                    menubar.Action = PdfAction.JavaScript(js, stamper.Writer);
                    // Add the annotation
                    stamper.AddAnnotation(menubar, 1);
                    // Create the advertisement annotation for the content
                    rect   = new Rectangle(400, 550, 545, 772);
                    button = new PushbuttonField(
                        stamper.Writer, rect, "advertisement"
                        );
                    button.BackgroundColor = BaseColor.WHITE;
                    button.BorderColor     = BaseColor.RED;
                    button.Text            = "Buy the book iText in Action 2nd edition";
                    button.Template        = stamper.GetImportedPage(ad, 1);
                    button.Layout          = PushbuttonField.LAYOUT_ICON_TOP_LABEL_BOTTOM;
                    PdfFormField advertisement = button.Field;
                    advertisement.Action = new PdfAction(
                        "http://www.1t3xt.com/docs/book.php"
                        );
                    // Add the annotation
                    stamper.AddAnnotation(advertisement, 1);
                }
                return(ms.ToArray());
            }
        }
Example #10
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            // Create a reader
            PdfReader reader = new PdfReader(src);
            int       n      = reader.NumberOfPages;

            using (MemoryStream ms = new MemoryStream())
            {
                // Create a stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Create pushbutton 1
                    PushbuttonField saveAs = new PushbuttonField(
                        stamper.Writer,
                        new Rectangle(636, 10, 716, 30),
                        "Save"
                        );
                    saveAs.BorderColor = BaseColor.BLACK;
                    saveAs.Text        = "Save";
                    saveAs.TextColor   = BaseColor.RED;
                    saveAs.Layout      = PushbuttonField.LAYOUT_LABEL_ONLY;
                    saveAs.Rotation    = 90;
                    PdfAnnotation saveAsButton = saveAs.Field;
                    saveAsButton.Action = PdfAction.JavaScript(
                        "app.execMenuItem('SaveAs')", stamper.Writer
                        );
                    // Create pushbutton 2
                    PushbuttonField mail = new PushbuttonField(
                        stamper.Writer,
                        new Rectangle(736, 10, 816, 30),
                        "Mail"
                        );
                    mail.BorderColor = BaseColor.BLACK;
                    mail.Text        = "Mail";
                    mail.TextColor   = BaseColor.RED;
                    mail.Layout      = PushbuttonField.LAYOUT_LABEL_ONLY;
                    mail.Rotation    = 90;
                    PdfAnnotation mailButton = mail.Field;
                    mailButton.Action = PdfAction.JavaScript(
                        "app.execMenuItem('AcroSendMail:SendMail')",
                        stamper.Writer
                        );
                    // Add the annotations to every page of the document
                    for (int page = 1; page <= n; page++)
                    {
                        stamper.AddAnnotation(saveAsButton, page);
                        stamper.AddAnnotation(mailButton, page);
                    }
                }
                return(ms.ToArray());
            }
        }
Example #11
0
// ---------------------------------------------------------------------------

        /**
         * Creates a Phrase with the name and given name of a director
         * using different fonts.
         * @param r the DbDataReader containing director records.
         */
        public Paragraph CreateDirectorParagraph(PdfWriter writer, DbDataReader r)
        {
            string n    = r["name"].ToString();
            Chunk  name = new Chunk(n);

            name.SetAction(PdfAction.JavaScript(
                               string.Format("findDirector('{0}');", n),
                               writer
                               ));
            name.Append(", ");
            name.Append(r["given_name"].ToString());
            return(new Paragraph(name));
        }
Example #12
0
        public void SaveChanges()
        {
            var xmlDocument = XfaXml.GenerateXML(Fields);

            if (javascriptBuilder.Length > 0)
            {
                var jsPdf = PdfAction.JavaScript(javascriptBuilder.ToString(), PdfStamper.Writer, true);

                PdfStamper.Writer.AddJavaScript("XfaCustomJavascriptCall", jsPdf);
            }

            PdfStamper.AcroFields.Xfa.FillXfaForm(xmlDocument);
        }
        // ---------------------------------------------------------------------------

        /**
         * Creates a PDF document.
         */
        public byte[] CreatePdf()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // step 1
                using (Document document = new Document())
                {
                    // step 2
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    // step 3
                    document.Open();
                    // step 4
                    PdfOutline          root = writer.RootOutline;
                    PdfOutline          movieBookmark;
                    PdfOutline          link;
                    String              title;
                    IEnumerable <Movie> movies = PojoFactory.GetMovies();
                    foreach (Movie movie in movies)
                    {
                        title = movie.MovieTitle;
                        if ("3-Iron".Equals(title))
                        {
                            title = "\ube48\uc9d1";
                        }
                        movieBookmark = new PdfOutline(root,
                                                       new PdfDestination(
                                                           PdfDestination.FITH, writer.GetVerticalPosition(true)
                                                           ),
                                                       title, true
                                                       );
                        movieBookmark.Style = Font.BOLD;
                        link = new PdfOutline(movieBookmark,
                                              new PdfAction(String.Format(RESOURCE, movie.Imdb)),
                                              "link to IMDB"
                                              );
                        link.Color = BaseColor.BLUE;
                        new PdfOutline(movieBookmark,
                                       PdfAction.JavaScript(
                                           String.Format(INFO, movie.Year, movie.Duration),
                                           writer
                                           ),
                                       "instant info"
                                       );
                        document.Add(new Paragraph(movie.MovieTitle));
                        document.Add(PojoToElementFactory.GetDirectorList(movie));
                        document.Add(PojoToElementFactory.GetCountryList(movie));
                    }
                }
                return(ms.ToArray());
            }
        }
Example #14
0
// ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            PdfReader reader = new PdfReader(src);

            using (MemoryStream ms = new MemoryStream()) {
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    stamper.Writer.AddJavaScript(File.ReadAllText(RESOURCE));
                    AcroFields      form = stamper.AcroFields;
                    AcroFields.Item fd   = form.GetFieldItem("married");

                    PdfDictionary dictYes =
                        (PdfDictionary)PdfReader.GetPdfObject(fd.GetWidgetRef(0));
                    PdfDictionary yesAction = dictYes.GetAsDict(PdfName.AA);
                    if (yesAction == null)
                    {
                        yesAction = new PdfDictionary();
                    }
                    yesAction.Put(
                        new PdfName("Fo"),
                        PdfAction.JavaScript("ReadOnly = false);", stamper.Writer)
                        );
                    dictYes.Put(PdfName.AA, yesAction);

                    PdfDictionary dictNo =
                        (PdfDictionary)PdfReader.GetPdfObject(fd.GetWidgetRef(1));
                    PdfDictionary noAction = dictNo.GetAsDict(PdfName.AA);
                    if (noAction == null)
                    {
                        noAction = new PdfDictionary();
                    }
                    noAction.Put(
                        new PdfName("Fo"),
                        PdfAction.JavaScript("ReadOnly = true);", stamper.Writer)
                        );
                    dictNo.Put(PdfName.AA, noAction);

                    PdfWriter       writer = stamper.Writer;
                    PushbuttonField button = new PushbuttonField(
                        writer, new Rectangle(40, 690, 200, 710), "submit"
                        );
                    button.Text    = "validate and submit";
                    button.Options = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
                    PdfFormField validateAndSubmit = button.Field;
                    validateAndSubmit.Action = PdfAction.JavaScript(
                        "validate();", stamper.Writer
                        );
                    stamper.AddAnnotation(validateAndSubmit, 1);
                }
                return(ms.ToArray());
            }
        }
Example #15
0
        // ---------------------------------------------------------------------------

        /**
         * Adds a popup.
         * @param stamper the PdfStamper to which the annotation needs to be added
         * @param rect the position of the annotation
         * @param title the annotation title
         * @param contents the annotation content
         * @param imdb the IMDB number of the movie used as name of the annotation
         */
        public void AddPopup(PdfStamper stamper, Rectangle rect,
                             String title, String contents, String imdb)
        {
            // Create the text annotation
            PdfAnnotation text = PdfAnnotation.CreateText(
                stamper.Writer,
                rect, title, contents, false, "Comment"
                );

            text.Name  = string.Format("IMDB{0}", imdb);
            text.Flags = PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_NOVIEW;
            // Create the popup annotation
            PdfAnnotation popup = PdfAnnotation.CreatePopup(
                stamper.Writer,
                new Rectangle(
                    rect.Left + 10, rect.Bottom + 10,
                    rect.Left + 200, rect.Bottom + 100
                    ),
                null, false
                );

            // Add the text annotation to the popup
            popup.Put(PdfName.PARENT, text.IndirectReference);
            // Declare the popup annotation as popup for the text
            text.Put(PdfName.POPUP, popup.IndirectReference);
            // Add both annotations
            stamper.AddAnnotation(text, 1);
            stamper.AddAnnotation(popup, 1);
            // Create a button field
            PushbuttonField field = new PushbuttonField(
                stamper.Writer, rect,
                string.Format("b{0}", imdb)
                );
            PdfAnnotation widget = field.Field;
            // Show the popup onMouseEnter
            PdfAction enter = PdfAction.JavaScript(
                string.Format(JS1, imdb), stamper.Writer
                );

            widget.SetAdditionalActions(PdfName.E, enter);
            // Hide the popup onMouseExit
            PdfAction exit = PdfAction.JavaScript(
                string.Format(JS2, imdb), stamper.Writer
                );

            widget.SetAdditionalActions(PdfName.X, exit);
            // Add the button annotation
            stamper.AddAnnotation(widget, 1);
        }
Example #16
0
            public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
            {
                PdfWriter writer;

                PdfWriterWeakRef.TryGetTarget(out writer);
                if (writer == null)
                {
                    return;
                }
                var annot = PdfAnnotation.CreateLink(writer, position, PdfAnnotation.HIGHLIGHT_NONE,
                                                     PdfAction.JavaScript(
                                                         $"this.exportDataObject({{ cName: '{AttachmentName}', nLaunch: 2 }});", writer));

                annot.Border = new PdfBorderArray(0, 0, 0);
                writer.AddAnnotation(annot);
            }
Example #17
0
// ===========================================================================
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                TextField date = new TextField(
                    writer, new Rectangle(36, 806, 126, 780), "date"
                    );
                date.BorderColor = new GrayColor(0.2f);
                PdfFormField datefield = date.GetTextField();
                // enter something that resembles a date for this to work;
                // if PDF reader doesn't recognize as a date, the field is cleared
                datefield.SetAdditionalActions(
                    PdfName.V,
                    PdfAction.JavaScript("AFDate_FormatEx( 'dd-mm-yyyy' );", writer)
                    );
                writer.AddAnnotation(datefield);
                TextField name = new TextField(
                    writer, new Rectangle(130, 806, 256, 780), "name"
                    );
                name.BorderColor = new GrayColor(0.2f);
                PdfFormField namefield = name.GetTextField();
                namefield.SetAdditionalActions(
                    PdfName.FO,
                    PdfAction.JavaScript(
                        "app.alert('name field got the focus');", writer
                        )
                    );
                namefield.SetAdditionalActions(
                    PdfName.BL,
                    PdfAction.JavaScript("app.alert('name lost the focus');", writer)
                    );
                namefield.SetAdditionalActions(
                    PdfName.K,
                    PdfAction.JavaScript(
                        "event.change = event.change.toUpperCase();", writer
                        )
                    );
                writer.AddAnnotation(namefield);
            }
        }
Example #18
0
        private void SetPDFViewerPropertiesPost(PdfWriter writer)
        {
            if (EnablePDFAutomaticPrint)
            {
                string jsText = String.Empty;

                if (PDFAutomaticPrintWaitTime > 0)
                {
                    jsText = "var res = app.setTimeOut('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);', " + PDFAutomaticPrintWaitTime + ");";
                }
                else
                {
                    jsText = "var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);";
                }
                PdfAction js = PdfAction.JavaScript(jsText, writer);
                writer.AddJavaScript(js);
            }
        }
Example #19
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result (localhost)
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            // Create the reader
            PdfReader reader = new PdfReader(src);
            int       n      = reader.NumberOfPages;

            using (MemoryStream ms = new MemoryStream())
            {
                // Create the stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Get the writer (to add actions and annotations)
                    PdfWriter writer = stamper.Writer;
                    PdfAction action = PdfAction.GotoLocalPage(2,
                                                               new PdfDestination(PdfDestination.FIT), writer
                                                               );
                    writer.SetOpenAction(action);
                    action = PdfAction.JavaScript(
                        "app.alert('Think before you print');", writer
                        );
                    writer.SetAdditionalAction(PdfWriter.WILL_PRINT, action);
                    action = PdfAction.JavaScript(
                        "app.alert('Think again next time!');", writer
                        );
                    writer.SetAdditionalAction(PdfWriter.DID_PRINT, action);
                    action = PdfAction.JavaScript(
                        "app.alert('We hope you enjoy the festival');", writer
                        );
                    writer.SetAdditionalAction(PdfWriter.DOCUMENT_CLOSE, action);
                    action = PdfAction.JavaScript(
                        "app.alert('This day is reserved for people with an accreditation "
                        + "or an invitation.');",
                        writer
                        );
                    stamper.SetPageAction(PdfWriter.PAGE_OPEN, action, 1);
                    action = PdfAction.JavaScript(
                        "app.alert('You can buy tickets for all the other days');", writer
                        );
                    stamper.SetPageAction(PdfWriter.PAGE_CLOSE, action, 1);
                }
                return(ms.ToArray());
            }
        }
Example #20
0
        // ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the file dest as result (localhost)
         * @param src the original PDF
         */
        public byte[] ManipulatePdf(byte[] src)
        {
            // Create the reader
            PdfReader reader = new PdfReader(src);
            int       n      = reader.NumberOfPages;

            using (MemoryStream ms = new MemoryStream())
            {
                // Create the stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Add JavaScript
                    jsString = File.ReadAllText(
                        Path.Combine(Utility.ResourceJavaScript, RESOURCE)
                        );
                    stamper.JavaScript = jsString;
                    // Create a Chunk with a chained action
                    PdfContentByte canvas;
                    Chunk          chunk  = new Chunk("print this page");
                    PdfAction      action = PdfAction.JavaScript(
                        "app.alert('Think before you print!');",
                        stamper.Writer
                        );
                    action.Next(PdfAction.JavaScript(
                                    "printCurrentPage(this.pageNum);",
                                    stamper.Writer
                                    ));
                    action.Next(new PdfAction("http://www.panda.org/savepaper/"));
                    chunk.SetAction(action);
                    Phrase phrase = new Phrase(chunk);
                    // Add this Chunk to every page
                    for (int i = 0; i < n;)
                    {
                        canvas = stamper.GetOverContent(++i);
                        ColumnText.ShowTextAligned(
                            canvas, Element.ALIGN_RIGHT, phrase, 816, 18, 0
                            );
                    }
                }
                return(ms.ToArray());
            }
        }
Example #21
0
        public void AddSubmitButton()
        {
            Rectangle       rect   = new Rectangle(50, 50, 100, 10);
            PushbuttonField button = new PushbuttonField(writer, rect, "postSubmit")
            {
                FontSize        = 8,
                BackgroundColor = BaseColor.LIGHT_GRAY,
                BorderColor     = GrayColor.BLACK,
                BorderWidth     = 1f,
                BorderStyle     = PdfBorderDictionary.STYLE_BEVELED,
                TextColor       = GrayColor.GREEN,
                Text            = "Submit",
                Visibility      = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT
            };
            PdfFormField field      = button.Field;
            String       javascript = "validate();";

            field.Action = PdfAction.JavaScript(javascript, writer);
            stamper.AddAnnotation(field, 1);
        }
        public void pPDF()

        {
            //Open existing PDF
            Document  document = new Document(PageSize.LETTER);
            PdfReader reader   = new PdfReader(Server.MapPath("~/Report/nasser7.pdf"));

            //Getting a instance of new PDF writer
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/Report/nasser12.pdf"), FileMode.Create));

            document.Open();
            PdfContentByte cb = writer.DirectContent;

            int       i     = 0;
            int       p     = 0;
            int       n     = reader.NumberOfPages;
            Rectangle psize = reader.GetPageSize(1);

            float width  = psize.Width;
            float height = psize.Height;

            //Add Page to new document
            while (i < n)
            {
                document.NewPage();
                p += 1;
                i += 1;

                PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page1, 0, 0);
            }

            //Attach javascript to the document
            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);

            writer.AddJavaScript(jAction);
            document.Close();

            //Attach pdf to the iframe
            //frmPrint.Attributes("src") = "Print2.pdf";
        }
Example #23
0
        private byte[] AddInfo(string msg, Stream input, bool print = false)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (PdfReader reader = new PdfReader(input))
                    using (PdfStamper stamper = new PdfStamper(reader, ms))
                    {
                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            Rectangle pageSize = reader.GetPageSize(i);

                            float Rightx = pageSize.Width;
                            float Righty = 0;

                            float Centerx = pageSize.Width / 2;
                            //float Centery = 0;

                            float Leftx = 0;
                            float Lefty = 0;

                            PdfContentByte ContentByte = stamper.GetOverContent(i);

                            if (print)
                            {
                                // Insert JavaScript to print the document after a fraction of a second (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, stamper.Writer);
                                stamper.Writer.AddJavaScript(js);
                            }

                            //var downloads = "# " + downloads.ToString();
                            AddQRCode(ContentByte, msg, Rightx, Righty, 3);
                            //AddText(ContentByte, "# " + downloads.ToString(), Centerx, Centery, 3);
                            AddTimeStamp(ContentByte, Leftx, Lefty, 3);
                        }
                    }

                return(ms.ToArray());
            }
        }
Example #24
0
        // ---------------------------------------------------------------------------

        /**
         * Create a pushbutton for a key
         * @param writer the PdfWriter
         * @param rect the position of the key
         * @param btn the label for the key
         * @param script the script to be executed when the button is pushed
         */
        public void AddPushButton(PdfWriter writer, Rectangle rect,
                                  String btn, String script)
        {
            float        w          = rect.Width;
            float        h          = rect.Height;
            PdfFormField pushbutton = PdfFormField.CreatePushButton(writer);

            pushbutton.FieldName = "btn_" + btn;
            pushbutton.SetWidget(rect, PdfAnnotation.HIGHLIGHT_PUSH);
            PdfContentByte cb = writer.DirectContent;

            pushbutton.SetAppearance(
                PdfAnnotation.APPEARANCE_NORMAL,
                CreateAppearance(cb, btn, BaseColor.GRAY, w, h)
                );
            pushbutton.SetAppearance(
                PdfAnnotation.APPEARANCE_ROLLOVER,
                CreateAppearance(cb, btn, BaseColor.RED, w, h)
                );
            pushbutton.SetAppearance(
                PdfAnnotation.APPEARANCE_DOWN,
                CreateAppearance(cb, btn, BaseColor.BLUE, w, h)
                );
            pushbutton.SetAdditionalActions(
                PdfName.U,
                PdfAction.JavaScript(script, writer)
                );
            pushbutton.SetAdditionalActions(
                PdfName.E, PdfAction.JavaScript(
                    "this.showMove('" + btn + "');", writer
                    )
                );
            pushbutton.SetAdditionalActions(
                PdfName.X, PdfAction.JavaScript(
                    "this.showMove(' ');", writer
                    )
                );
            writer.AddAnnotation(pushbutton);
        }
Example #25
0
        public void MakePrintable(string sourcePath, string targetPath)
        {
            int       pageNumber = 1;
            PdfReader reader     = new PdfReader(sourcePath);
            Rectangle size       = reader.GetPageSizeWithRotation(pageNumber);
            Document  document   = new Document(size);
            PdfWriter writer     = PdfWriter.GetInstance(document, new FileStream(targetPath, FileMode.Create, FileAccess.Write));

            document.Open();
            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);

            writer.AddJavaScript(jAction);
            PdfContentByte cb = writer.DirectContent;

            document.NewPage();
            PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);

            cb.AddTemplate(page, 0, 0);
            reader.Close();
            document.Close();
            writer.Close();
            document.Close();
        }
Example #26
0
// ---------------------------------------------------------------------------

        /**
         * Show keys and values passed to the query string with GET
         */
        protected void DoGet(byte[] pdf, Stream stream)
        {
            // We get a resource from our web app
            PdfReader reader = new PdfReader(pdf);

            // Now we create the PDF
            using (PdfStamper stamper = new PdfStamper(reader, stream)) {
                // We add a submit button to the existing form
                PushbuttonField button = new PushbuttonField(
                    stamper.Writer, new Rectangle(90, 660, 140, 690), "submit"
                    );
                button.Text            = "POST";
                button.BackgroundColor = new GrayColor(0.7f);
                button.Visibility      = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT;
                PdfFormField submit = button.Field;
                submit.Action = PdfAction.CreateSubmitForm(
                    WebContext.Request.RawUrl, null, 0
                    );
                stamper.AddAnnotation(submit, 1);
                // We add an extra field that can be used to upload a file
                TextField file = new TextField(
                    stamper.Writer, new Rectangle(160, 660, 470, 690), "image"
                    );
                file.Options         = TextField.FILE_SELECTION;
                file.BackgroundColor = new GrayColor(0.9f);
                PdfFormField upload = file.GetTextField();
                upload.SetAdditionalActions(PdfName.U,
                                            PdfAction.JavaScript(
                                                "this.getField('image').browseForFileToSubmit();"
                                                + "this.getField('submit').setFocus();",
                                                stamper.Writer
                                                )
                                            );
                stamper.AddAnnotation(upload, 1);
            }
        }
Example #27
0
        protected void btnprintq_Click(object sender, EventArgs e)
        {
            Warning[] warnings;
            string[]  streamids;
            string    mimeType;
            string    encoding;
            string    extension;

            byte[] bytes = rptReciptPrint.LocalReport.Render("PDF", null, out mimeType,
                                                             out encoding, out extension, out streamids, out warnings);

            FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"), FileMode.Create);

            fs.Write(bytes, 0, bytes.Length);
            fs.Close();

            //Open exsisting pdf
            Document  document = new Document(PageSize.LETTER);
            PdfReader reader   = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf"));
            //Getting a instance of new pdf wrtiter

            string uploadPath = Server.MapPath("~/StudentRecipts");

            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            string stdpath = Server.MapPath("~/StudentRecipts/" + hdnAdmissionid.Value);

            if (!Directory.Exists(stdpath))
            {
                Directory.CreateDirectory(stdpath);
            }
            string    intallno = Request.QueryString["InstallmentNo"].ToString();
            string    filename = hdnAdmissionid.Value + "_" + h3StudentName.InnerText + "_" + intallno + ".pdf";
            string    path     = Path.Combine(stdpath, filename);
            PdfWriter writer   = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));

            document.Open();
            PdfContentByte cb = writer.DirectContent;

            int       i     = 0;
            int       p     = 0;
            int       n     = reader.NumberOfPages;
            Rectangle psize = reader.GetPageSize(1);

            float width  = psize.Width;
            float height = psize.Height;

            //Add Page to new document
            while (i < n)
            {
                document.NewPage();
                p++;
                i++;

                PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page1, 0, 0);
            }

            //Attach javascript to the document
            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);

            writer.AddJavaScript(jAction);
            document.Close();

            //Attach pdf to the iframe
            frmPrint.Attributes["src"] = "~/StudentRecipts/" + hdnAdmissionid.Value + "/" + filename;
        }
Example #28
0
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.IsAuthenticated)
            {
                try
                {
                    var tipRel        = HttpUtility.UrlDecode(HttpContext.Current.Request["tipRel"]);
                    var parametrosRel = HttpUtility.UrlDecode(HttpContext.Current.Request["params"]);
                    int rlt_id;

                    if (int.TryParse(tipRel, out rlt_id))
                    {
                        string    mimeType;
                        string    encoding;
                        string    fileNameExtension;
                        Warning[] warnings;
                        string[]  streamids;
                        byte[]    exportBytes;

                        //Recebe os dados do relatório
                        CFG_Relatorio rpt = new CFG_Relatorio()
                        {
                            rlt_id = rlt_id
                        };
                        CFG_RelatorioBO.GetEntity(rpt);
                        if (rpt.IsNew)
                        {
                            throw new ValidationException("Relatório não encontrado.");
                        }
                        //Configurações do Relatório
                        CFG_ServidorRelatorio rptServer = CFG_ServidorRelatorioBO.CarregarServidorRelatorioPorEntidade(
                            this.__SessionWEB.__UsuarioWEB.Usuario.ent_id
                            , ApplicationWEB.AppMinutosCacheLongo
                            );

                        if (rptServer.IsNew)
                        {
                            throw new ValidationException("O servidor de relatório não está configurado.");
                        }

                        //Carrega os parâmetros do relatório
                        MSReportServerParameters param = new MSReportServerParameters(parametrosRel);
                        //Checa o modo de processamento do servidor
                        if (rptServer.srr_remoteServer)
                        {
                            Microsoft.Reporting.WebForms.ReportViewer ReportViewerRel = new Microsoft.Reporting.WebForms.ReportViewer();

                            //Configura o reportviewer
                            ReportViewerRel.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
                            Uri urlReport = new Uri(rptServer.srr_diretorioRelatorios);
                            ReportViewerRel.ServerReport.ReportServerUrl         = urlReport;
                            ReportViewerRel.ServerReport.ReportServerCredentials = new MSReportServerCredentials(rptServer.srr_usuario, rptServer.srr_senha, rptServer.srr_dominio);
                            ReportViewerRel.ServerReport.ReportPath = String.Concat(rptServer.srr_pastaRelatorios, rpt.rlt_nome);
                            ReportViewerRel.ServerReport.SetParameters(param.getReportParameters());

                            //Carrega o relatório
                            exportBytes = ReportViewerRel.ServerReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streamids, out warnings);


                            #region PDF Sharp
                            //MemoryStream fs = new MemoryStream(exportBytes);
                            //PdfDocument document = PdfReader.Open(fs, PdfDocumentOpenMode.Modify);
                            //PdfDictionary dictJS = new PdfDictionary(document);
                            //dictJS.Elements["/S"] = new PdfName("/JavaScript");
                            //dictJS.Elements["/JS"] = new PdfString("this.print(true);\r");

                            //document.Internals.AddObject(dictJS);
                            //document.Internals.Catalog.Elements["/OpenAction"] = PdfInternals.GetReference(dictJS);


                            //MemoryStream ms = new MemoryStream();
                            //document.Save(ms, false);

                            #endregion

                            #region ITextSharp

                            MemoryStream ms = new MemoryStream();

                            PdfReader reader   = new PdfReader(exportBytes);
                            Document  document = null;
                            PdfCopy   writer   = null;
                            int       n        = reader.NumberOfPages;

                            document = new Document(reader.GetPageSizeWithRotation(1));
                            writer   = new PdfCopy(document, ms);
                            document.Open();
                            PdfImportedPage page;
                            for (int i = 0; i < n;)
                            {
                                ++i;
                                page = writer.GetImportedPage(reader, i);
                                writer.AddPage(page);
                            }
                            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
                            writer.AddJavaScript(jAction);

                            document.Close();
                            writer.Close();

                            #endregion

                            HttpResponse response = HttpContext.Current.Response;
                            response.ClearContent();
                            response.ClearHeaders();
                            response.Buffer = true;
                            response.Cache.SetCacheability(HttpCacheability.Private);
                            response.ContentType = "application/pdf";

                            response.AddHeader("Content-Disposition", "inline;");
                            response.BinaryWrite(ms.ToArray());
                            ms.Close();
                            HttpContext.Current.ApplicationInstance.CompleteRequest();

                            response.End();
                        }
                    }
                }
                catch (ThreadAbortException)
                {
                }
                catch (Exception ex)
                {
                    MSTech.GestaoEscolar.Web.WebProject.ApplicationWEB._GravaErro(ex);
                }
            }
        }
Example #29
0
// ---------------------------------------------------------------------------

        /**
         * Creates a PDF document.
         */
        public byte[] CreatePdf()
        {
            using (MemoryStream ms = new MemoryStream()) {
                using (Document document = new Document()) {
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    document.Open();
                    jsString = File.ReadAllText(
                        Path.Combine(Utility.ResourceJavaScript, RESOURCE)
                        );
                    writer.AddJavaScript(jsString);

                    PdfContentByte canvas = writer.DirectContent;
                    Font           font   = new Font(Font.FontFamily.HELVETICA, 18);
                    Rectangle      rect;
                    PdfFormField   field;
                    PdfFormField   radiogroup = PdfFormField.CreateRadioButton(writer, true);
                    radiogroup.FieldName = "language";
                    RadioCheckField radio;
                    for (int i = 0; i < LANGUAGES.Length; i++)
                    {
                        rect                  = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40);
                        radio                 = new RadioCheckField(writer, rect, null, LANGUAGES[i]);
                        radio.BorderColor     = GrayColor.GRAYBLACK;
                        radio.BackgroundColor = GrayColor.GRAYWHITE;
                        radio.CheckType       = RadioCheckField.TYPE_CIRCLE;
                        field                 = radio.RadioField;
                        radiogroup.AddKid(field);
                        ColumnText.ShowTextAligned(
                            canvas, Element.ALIGN_LEFT,
                            new Phrase(LANGUAGES[i], font), 70, 790 - i * 40, 0
                            );
                    }
                    writer.AddAnnotation(radiogroup);

                    PdfAppearance[] onOff = new PdfAppearance[2];
                    onOff[0] = canvas.CreateAppearance(20, 20);
                    onOff[0].Rectangle(1, 1, 18, 18);
                    onOff[0].Stroke();
                    onOff[1] = canvas.CreateAppearance(20, 20);
                    onOff[1].SetRGBColorFill(255, 128, 128);
                    onOff[1].Rectangle(1, 1, 18, 18);
                    onOff[1].FillStroke();
                    onOff[1].MoveTo(1, 1);
                    onOff[1].LineTo(19, 19);
                    onOff[1].MoveTo(1, 19);
                    onOff[1].LineTo(19, 1);
                    onOff[1].Stroke();
                    RadioCheckField checkbox;
                    for (int i = 0; i < LANGUAGES.Length; i++)
                    {
                        rect     = new Rectangle(180, 806 - i * 40, 200, 788 - i * 40);
                        checkbox = new RadioCheckField(writer, rect, LANGUAGES[i], "on");
                        // checkbox.CheckType = RadioCheckField.TYPE_CHECK;
                        field = checkbox.CheckField;
                        field.SetAppearance(
                            PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0]
                            );
                        field.SetAppearance(
                            PdfAnnotation.APPEARANCE_NORMAL, "On", onOff[1]
                            );
                        writer.AddAnnotation(field);
                        ColumnText.ShowTextAligned(
                            canvas, Element.ALIGN_LEFT,
                            new Phrase(LANGUAGES[i], font), 210,
                            790 - i * 40, 0
                            );
                    }
                    rect = new Rectangle(300, 806, 370, 788);
                    PushbuttonField button = new PushbuttonField(writer, rect, "Buttons");
                    button.BackgroundColor          = new GrayColor(0.75f);
                    button.BorderColor              = GrayColor.GRAYBLACK;
                    button.BorderWidth              = 1;
                    button.BorderStyle              = PdfBorderDictionary.STYLE_BEVELED;
                    button.TextColor                = GrayColor.GRAYBLACK;
                    button.FontSize                 = 12;
                    button.Text                     = "Push me";
                    button.Layout                   = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT;
                    button.ScaleIcon                = PushbuttonField.SCALE_ICON_ALWAYS;
                    button.ProportionalIcon         = true;
                    button.IconHorizontalAdjustment = 0;
                    button.Image                    = Image.GetInstance(
                        Path.Combine(Utility.ResourceImage, IMAGE)
                        );
                    field        = button.Field;
                    field.Action = PdfAction.JavaScript("this.showButtonState()", writer);
                    writer.AddAnnotation(field);
                }
                return(ms.ToArray());
            }
        }
        public ActionResult printPDF()
        {
            string pdfBody = string.Empty;

            pdfBody += "<table>";
            pdfBody += "<tr>";
            pdfBody += "<td> C </ td >";
            pdfBody += "<td> RoseWater</td>";
            pdfBody += "<td></td>";
            pdfBody += "</tr>";
            pdfBody += "<tr>";
            pdfBody += "<td>Date:01/06/201</td>";
            pdfBody += "<td>Name:Nasser</td>";
            pdfBody += "<td>Te:1234566</td>";
            pdfBody += "</tr>";


            foreach (var itm in db.Customers.OrderBy(x => x.CustName).ToList())
            {
                pdfBody += "<tr>";
                pdfBody += "<td>" + itm.CustName + "</td>";
                pdfBody += "<td>" + itm.Tel + "</td>";
                pdfBody += "<td>" + itm.CustId + "</td>";
                pdfBody += "</tr>";
            }
            pdfBody += "</table>";
            Document document = new Document();
            //string filenm = "UserList.pdf";
            string filenm = "BillNo-" + DateTime.Now.Ticks + ".pdf";
            var    fpath  = HttpContext.Server.MapPath("~/Documents/PDFDocuments/");
            //PngWriter.GetInstance(document, new FileStream(fpath + filenm, FileMode.Create));

            PdfWriter oPdfWriter = PdfWriter.GetInstance(document, new FileStream(fpath + filenm, FileMode.Create));

            document.Open();
            //If you want to add phrase:

            Phrase titl = new Phrase("\nCustomer Copy\n");

            titl.Font.SetStyle(Font.BOLD);
            document.Add(titl);

            iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();

            iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);

            hw.Parse(new StringReader(pdfBody));
            var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Content/images/logo.png"));

            logo.SetAbsolutePosition(300, 750);
            document.Add(logo);

            string jsText = "var res = app.setTimeOut(‘var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);’, 200);";

            PdfAction js = PdfAction.JavaScript(jsText, oPdfWriter);

            oPdfWriter.AddJavaScript(js);

            document.Close();

            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "inline;filename=" + filenm + "");
            Response.ContentType = "application/pdf";

            Response.WriteFile(HttpContext.Server.MapPath("~/Documents/PDFDocuments/") + filenm);
            Response.Flush();
            Response.Clear();

            //printMyPDF("UserList.pdf");
            ViewBag.myPDF = filenm;
            return(View());
        }