locked
Placing Text on Multiple Imported PDF Pages with iTextSharp RRS feed

  • Question

  • User1122355199 posted

    Hello everyone and thanks for your help in advance.  I am trying to create a web application that utilizes iTextSharp to import a multi-page pdf, the place text on the different pages, in other words a certain text for page 1, different text for page, etc.  I've successfully imported the pdf, but the text is escaping me.  Here is my code:

                PdfReader reader = null;
                Document sourceDocument = null;
                PdfCopy pdfCopyProvider = null;
                PdfImportedPage importedPage = null;
    
                int startPage = 1;
                int endPage = 2;
    
                try
                {
    
                    string sourcePdfPath = Server.MapPath(path);
                    // Intialize a new PdfReader instance with the contents of the source Pdf file:
                    reader = new PdfReader(sourcePdfPath);
    
                    // For simplicity, I am assuming all the pages share the same size
                    // and rotation as the first page:
                    sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage));
    
                    // Initialize an instance of the PdfCopyClass with the source 
                    // document and an output file stream:
                    //
                    MemoryStream ms = new MemoryStream();
                    pdfCopyProvider = new PdfCopy(sourceDocument, ms);
                    //
                    //pdfCopyProvider = new PdfCopy(sourceDocument,
                    //    new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
    
                    sourceDocument.Open();
    
                    // Walk the specified range and add the page copies to the output file:
                    for (int i = startPage; i <= endPage; i++)
                    {
                        importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                        pdfCopyProvider.AddPage(importedPage);
                    }
    
                    PdfContentByte cb = pdfCopyProvider.DirectContent;
    
                PdfReader reader = null;
                Document sourceDocument = null;
                PdfCopy pdfCopyProvider = null;
                PdfImportedPage importedPage = null;
    
                int startPage = 1;
                int endPage = 2;
    
    
    
                try
                {
    
                    string sourcePdfPath = Server.MapPath(path);
                    // Intialize a new PdfReader instance with the contents of the source Pdf file:
                    reader = new PdfReader(sourcePdfPath);
    
                    // For simplicity, I am assuming all the pages share the same size
                    // and rotation as the first page:
                    sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage));
    
                    // Initialize an instance of the PdfCopyClass with the source 
                    // document and an output file stream:
                    //
                    MemoryStream ms = new MemoryStream();
                    pdfCopyProvider = new PdfCopy(sourceDocument, ms);
                    //
                    //pdfCopyProvider = new PdfCopy(sourceDocument,
                    //    new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
    
                    sourceDocument.Open();
    
                    // Walk the specified range and add the page copies to the output file:
                    for (int i = startPage; i <= endPage; i++)
                    {
                        importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                        pdfCopyProvider.AddPage(importedPage);
                    }
    
                    PdfContentByte cb = pdfCopyProvider.DirectContent;
    
                    //select the font properties 
                    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    cb.SetColorFill(BaseColor.DARK_GRAY);
                    cb.SetFontAndSize(bf, 12);
    
                    //write the Patient Name
                    cb.BeginText();
                    //put the alignment and coordinates here 
                    cb.ShowTextAligned(3, "Hello", 200, 200, 0);
                    cb.EndText();
    
                    sourceDocument.Close();
                    reader.Close();
    
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=file.pdf");
                    Response.Buffer = true;
                    Response.Clear();
                    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
                    Response.OutputStream.Flush();
                    Response.End();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
    
    
            }
    
                    sourceDocument.Close();
                    reader.Close();
    
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=file.pdf");
                    Response.Buffer = true;
                    Response.Clear();
                    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
                    Response.OutputStream.Flush();
                    Response.End();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
    
    
            }

    Any help would be appreciated.

    Friday, February 9, 2018 6:00 PM

All replies

  • User283571144 posted

    Hi kmcnet,

    Hello everyone and thanks for your help in advance.  I am trying to create a web application that utilizes iTextSharp to import a multi-page pdf, the place text on the different pages, in other words a certain text for page 1, different text for page, etc.  I've successfully imported the pdf, but the text is escaping me.  Here is my code:

    According to your description and codes, I found you used PdfCopy to write new text to the PDF.

    As far as I know, if you want to write the text to the PDF file, you should use PdfWriter.

    More details, you could refer to below codes sample.

          protected void Button1_Click(object sender, EventArgs e)
            {
    
                PdfReader reader = null;
                Document sourceDocument = null;
                 PdfCopy pdfCopyProvider = null;
                PdfImportedPage importedPage = null;
    
                int startPage = 1;
                int endPage = 2;
    
    
    
                string path = @"D:\test.pdf";
                string newFile = @"D:\copyfile.pdf";
    
                try
                {
    
                    //string sourcePdfPath = Server.MapPath(path);
                    // Intialize a new PdfReader instance with the contents of the source Pdf file:
                    reader = new PdfReader(path);
    
                    // For simplicity, I am assuming all the pages share the same size
                    // and rotation as the first page:
                    sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage));
    
                    // Initialize an instance of the PdfCopyClass with the source 
                    // document and an output file stream:
                    //
    
                    FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
    
                    pdfCopyProvider = new PdfCopy(sourceDocument, fs);
                    //
                    //pdfCopyProvider = new PdfCopy(sourceDocument,
                    //    new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
    
                    sourceDocument.Open();
    
                    // Walk the specified range and add the page copies to the output file:
                    for (int i = startPage; i <= endPage; i++)
                    {
                        importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                        pdfCopyProvider.AddPage(importedPage);
                    }
    
                 
                    sourceDocument.Close();
                    reader.Close();
                    pdfCopyProvider.Close();
    
                    MemoryStream ms = startwrite(newFile);
    
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=file.pdf");
                    Response.Buffer = true;
                    Response.Clear();
                    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
                    Response.OutputStream.Flush();
                    Response.End();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
    
            }
    
    
            public static MemoryStream startwrite(string newpath)
            {
                var ms = new MemoryStream();
                using (var reader = new PdfReader(newpath))
                {
                   
                        var document = new Document(reader.GetPageSizeWithRotation(1));
                        var writer = PdfWriter.GetInstance(document, ms);
    
                        document.Open();
    
                        for (var i = 1; i <= reader.NumberOfPages; i++)
                        {
                            document.NewPage();
    
                            var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                            var importedPage = writer.GetImportedPage(reader, i);
    
                            var contentByte = writer.DirectContent;
                            contentByte.BeginText();
                            contentByte.SetFontAndSize(baseFont, 12);
    
                            var multiLineString = "Hello,\r\nWorld!".Split('\n');
    
                            foreach (var line in multiLineString)
                            {
                                contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
                            }
    
                            contentByte.EndText();
                            contentByte.AddTemplate(importedPage, 0, 0);
                        }
    
                        document.Close();
                        writer.Close();
                    return ms;
                }
            }

    Result:

    Best Regards,

    Brando

    Monday, February 12, 2018 6:50 AM