C# 在现有pdf内容c之后添加新段落#

C# 在现有pdf内容c之后添加新段落#,c#,pdf,itext,devexpress,C#,Pdf,Itext,Devexpress,我想显示后,pdf的最后一页像这张图片现有内容的段落 借助c#代码(使用任何开源pdf sdk或库) 这是我当前的代码。这是在新页面上添加文本,而不是在我的最后一页上。 我搜索并使用了大量来自互联网的代码,所有这些代码都在页面的绝对位置(wrt x,y坐标)上写入文本,这些文本与现有内容上的新文本重叠。我需要相对逻辑,在旧段落结束后追加新段落,就像我随附的照片演示一样 当前iTextSharp代码(使用此Dll:iTextSharp.Dll) string newparagraphText=

我想显示后,pdf的最后一页像这张图片现有内容的段落 借助c#代码(使用任何开源pdf sdk或库)

这是我当前的代码。这是在新页面上添加文本,而不是在我的最后一页上。 我搜索并使用了大量来自互联网的代码,所有这些代码都在页面的绝对位置(wrt x,y坐标)上写入文本,这些文本与现有内容上的新文本重叠。我需要相对逻辑,在旧段落结束后追加新段落,就像我随附的照片演示一样

当前iTextSharp代码(使用此Dll:iTextSharp.Dll)


string newparagraphText=memoEdit1.Text;
AddCommentsToFile(@“input.pdf”,newparagraphText);
私有静态字符串AddCommentsToFile(字符串文件名,字符串用户注释)
{
字符串outputFileName=@“Output.pdf”;
//步骤1:创建文档对象
文档=新文档();
尝试
{
//步骤2:我们创建一个侦听文档的编写器
PdfWriter writer=PdfWriter.GetInstance(文档,新文件流(outputFileName,FileMode.Create));
//步骤3:打开文档
document.Open();
PdfContentByte cb=writer.DirectContent;
//当前文件路径
字符串文件名=文件名;
//我们为文档创建一个阅读器
PdfReader reader=新的PdfReader(文件名);
PdfReader.unethicalreading=true;
对于(int pageNumber=1;pageNumber
可能不是实际的,但无论如何,可以确定内容的结束位置。在这里您可以看到示例:

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);
                }
            }
        }
    }

我用itextsharp实现了我的目标 演示代码:

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);
                    }
                }
使用系统;
使用System.Windows.Forms;
使用DevExpress.XtraEditors;
使用System.IO;
使用iTextSharp.text;
使用iTextSharp.text.pdf;
使用iTextSharp.text.pdf.parser;
private void ButtonEditPDF\u单击(对象发送者,事件参数e)
{
字符串fileInputPath=“input.pdf”;
System.Drawing.Bitmap Bitmap=new System.Drawing.Bitmap(40,60);//如果需要,可以使用任何图像
if(checkEditIsNewPage.Checked==true)
{
AddCommentsToFile_NewPage(fileInputPath,memoEdit1.Text,位图);//memoEdit1.Text或字符串段落
}
其他的
{
AddCommentsToFile_SamePage(fileInputPath,memoEdit1.Text,位图);//memoEdit1.Text或字符串段落
}
}
私有静态字符串AddCommentsToFile_NewPage(字符串文件名、字符串用户注释、System.Drawing.Bitmap位图)
{
字符串outputFileName=@“Output\u N.pdf”;
//步骤1:创建文档对象
文档=新文档();
尝试
{
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);
                }
            }
        }
    }
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);
                    }
                }