2
votes

i want to show paragraph after existing content of pdf last page like this pic with the help of c# code(with any open source pdf sdk or library)

enter image description here

this is my current code this is appending text on new page instead on my last page. i search and used lot of code from internet all write text on absolute position(wrt x,y coordinates) of page which overlap new text on existing content i need relative logic which append new paragraph after old paragraph end same like my attached photo demo.

current iTextSharp Code(using this Dll:itextsharp.dll)

using System.IO;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;

 string newparagraphText=memoEdit1.Text;
        AddCommentsToFile(@"input.pdf",newparagraphText);

         private static string AddCommentsToFile(string fileName, string userComments)
                {
                    string outputFileName = @"Output.pdf";
                    //Step 1: Create a Docuement-Object
                    Document document = new Document();
                    try
                    {
                        //Step 2: we create a writer that listens to the document
                        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create));

                        //Step 3: Open the document
                        document.Open();

                        PdfContentByte cb = writer.DirectContent;

                        //The current file path
                        string filename = fileName;

                        // we create a reader for the document
                        PdfReader reader = new PdfReader(filename);
                        PdfReader.unethicalreading = true;
                        for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
                        {
                            document.SetPageSize(reader.GetPageSizeWithRotation(1));
                            document.NewPage();

                            //Insert to Destination on the first page
                            if (pageNumber == 1)
                            {
                                Chunk fileRef = new Chunk(" ");
                                fileRef.SetLocalDestination(filename);
                                document.Add(fileRef);
                            }

                            PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
                            int rotation = reader.GetPageRotation(pageNumber);
                            if (rotation == 90 || rotation == 270)
                            {
                                cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);
                            }
                            else
                            {
                                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                            }
                        }

                        // Add a new page to the pdf file
                        document.NewPage();

                        Paragraph paragraph = new Paragraph();
                        iTextSharp.text.Font titleFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
                                                  , 15
                                                  , iTextSharp.text.Font.BOLD
                                                  , BaseColor.BLACK
                            );
                        Chunk titleChunk = new Chunk("Comments", titleFont);
                        paragraph.Add(titleChunk);
                        document.Add(paragraph);

                        paragraph = new Paragraph();
                        iTextSharp.text.Font textFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
                                                 , 12
                                                 , iTextSharp.text.Font.NORMAL
                                                 , BaseColor.BLACK
                            );
                        Chunk textChunk = new Chunk(userComments, textFont);
                        paragraph.Add(textChunk);

                        document.Add(paragraph);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    {
                        document.Close();
                    }
                    return outputFileName;
                }
2
I'm afraid this is a bit more complex than you're expecting, IF you're manipulating an existing pdf: There's no guarantee that the pdf in question contains enough information to identify the last paragraph. You can probably make do with some heuristics to extract the absolute position, using the information provided by text-extraction for example (see Joris' link). Using that, you can place your text below it, avoiding overlap with existing content - Samuel Huylebroeck
i am looking for c# example it is java example please help - sms247
The code should be very similar. So if you spend some effort in reading the example, you should be able to come up with the corresponding C# example yourself. - Joris Schellekens
i am not good in java please convert your code into c# if possible if not then dont worry i hope any c# expert will help me and answer my question thanks. - sms247

2 Answers

1
votes

i achieve my goal with itextsharp Demo code:

using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser; 

    private void ButtonEditPDF_Click(object sender, EventArgs e)
            {
            string fileInputPath = "input.pdf";            
                        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(40, 60);//use any image if you want
                        if (checkEditIsNewPage.Checked == true)
                        {
                            AddCommentsToFile_NewPage(fileInputPath , memoEdit1.Text,bitmap);//memoEdit1.Text or your string paragraph
                        }
                        else
                        {
                            AddCommentsToFile_SamePage(fileInputPath , memoEdit1.Text,bitmap);//memoEdit1.Text or your string paragraph
                        }
        }
        private static string AddCommentsToFile_NewPage(string fileName, string userComments, System.Drawing.Bitmap bitmap)
                {
                    string outputFileName = @"Output_N.pdf";
                    //Step 1: Create a Docuement-Object
                    Document document = new Document();
                    try
                    {
                        //Step 2: we create a writer that listens to the document
                        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create));

                        //Step 3: Open the document
                        document.Open();

                        PdfContentByte cb = writer.DirectContent;

                        //The current file path
                        string filename = fileName;

                        // we create a reader for the document
                        PdfReader reader = new PdfReader(filename);
                        PdfReader.unethicalreading = true;
                        for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
                        {
                            document.SetPageSize(reader.GetPageSizeWithRotation(1));
                            document.NewPage();

                            //Insert to Destination on the first page
                            if (pageNumber == 1)
                            {
                                Chunk fileRef = new Chunk(" ");
                                fileRef.SetLocalDestination(filename);
                                document.Add(fileRef);
                            }

                            PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
                            int rotation = reader.GetPageRotation(pageNumber);
                            if (rotation == 90 || rotation == 270)
                            {
                                cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);

                            }
                            else
                            {
                                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                            }
                        }

                        // Add a new page to the pdf file
                        document.NewPage();

                        Paragraph paragraph = new Paragraph();
                        iTextSharp.text.Font titleFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
                                                  , 15
                                                  , iTextSharp.text.Font.BOLD
                                                  , BaseColor.BLACK
                            );
                        Chunk titleChunk = new Chunk("Reamkrs", titleFont);
                        paragraph.Add(titleChunk);
                        document.Add(paragraph);

                        paragraph = new Paragraph();
                        iTextSharp.text.Font textFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
                                                 , 12
                                                 , iTextSharp.text.Font.NORMAL
                                                 , BaseColor.BLACK
                            );
                        Chunk textChunk = new Chunk(userComments, textFont);
                        paragraph.Add(textChunk);

                        document.Add(paragraph);
                        paragraph = new Paragraph();

                        document.Add(Chunk.NEWLINE);
                        Image logo = Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);
                        Phrase signature = new Phrase(new Chunk(logo, 0, -10, true));
                        signature.Add(new Chunk(Environment.NewLine));
                        paragraph.Add(signature);

                        document.Add(paragraph);




                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    {
                        document.Close();
                    }
                    return outputFileName;
                }
                private void AddCommentsToFile_SamePage(string file2, string text, System.Drawing.Bitmap bitmap)
                {
                    try
                    {
                        PdfReader reader = new PdfReader(new RandomAccessFileOrArray(file2), null);
                        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
                        TextMarginFinder finder = new TextMarginFinder();
                        PdfReader.unethicalreading = true;

                        using (PdfStamper stamper = new PdfStamper(reader, new FileStream(@"Output.pdf", FileMode.Create, FileAccess.Write)))
                        {
                            //   int pageNumber = reader.NumberOfPages;
                            //   finder = parser.ProcessContent(pageNumber, new TextMarginFinder());
                            PdfContentByte cb = stamper.GetOverContent(1);
                            Rectangle rect = new Rectangle(0, 0, 0, 0);
                            for (int i = 1; i <= reader.NumberOfPages; i++)
                            {
                                finder = parser.ProcessContent(i, new TextMarginFinder());
                                cb = stamper.GetOverContent(i);
                                rect = new Rectangle(
                                  finder.GetLlx(), finder.GetLly(),
                                  finder.GetWidth() + 90f, finder.GetHeight()
                                );
                                cb.Rectangle(rect);
                            }
                            cb.Stroke();
                            //  rect.Height = Size.Height;
                            var size = reader.GetPageSize(1);
                            iTextSharp.text.Font titleFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
                                                  , 15
                                                  , iTextSharp.text.Font.BOLD
                                                  , BaseColor.BLACK
                            );
                            iTextSharp.text.Font textFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA
                                                , 12
                                                , iTextSharp.text.Font.NORMAL
                                                , BaseColor.BLACK
                           );
                            Chunk titleChunk = new Chunk("Reamkrs", titleFont);
                            Phrase phrase = new Phrase(text,textFont);
                            // Image logo = Image.GetInstance("signature.png");
                           // System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(40, 60);
                            Image logo = Image.GetInstance(bitmap,System.Drawing.Imaging.ImageFormat.Bmp);
                            Phrase signature = new Phrase(new Chunk(logo,0,0,true));                   
                            ColumnText ct = new ColumnText(cb);
                            ct.SetSimpleColumn(rect);
                            ct.AddElement(titleChunk);
                            ct.AddElement(phrase);
                            ct.AddElement(new Chunk(Environment.NewLine));
                            ct.AddElement(signature);
                            ct.Go();
                            stamper.Close();
                            reader.Close();
                        }
                    }

                    catch (Exception ex)
                    {

                        MessageBox.Show("sbtn_Click : " + ex.Message);
                    }
                }
0
votes

maybe it is not actual but anyway it is possible to identify where content is ended. Here you can see the sample:

using System;
using System.Collections.Generic;
using System.IO;

using Apitron.PDF.Kit.FixedLayout;
using Apitron.PDF.Kit.FixedLayout.Content;
using Apitron.PDF.Kit.FixedLayout.PageProperties;

using FixedLayout.Resources;
using FixedLayout.ContentElements;
using FlowLayout.Content;

public void AddParagraph()
    {
        using (Stream stream = new FileStream("file.pdf", FileMode.Open, FileAccess.ReadWrite))
        {
            using (FixedDocument document = new FixedDocument(stream))
            {
                Page page = document.Pages[0];
                double minY = page.Boundary.MediaBox.Height;
                foreach(IContentElement element in page.Elements)
                {
                    if(element != null)
                    {
                        minY = Math.Min(element.Boundary.Bottom, minY);
                    }
                }

                TextBlock textBlock = new TextBlock("I want to show new paragraph here")
                {
                    Border = new Border(2),
                    BorderColor = RgbColors.Red,
                    Color = RgbColors.Red                
                };

                page.Content.SetTranslate(100, minY - 100);
                page.Content.AppendContentElement(textBlock, 100, 100);

                // incremental save
                // document.Save();
                // or simple save
                using (Stream outStream = new FileStream("out.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    document.Save(outStream);
                }
            }
        }
    }