简体   繁体   English

使用PDFsharp库向PDF文档添加额外的页面

[英]Add an extra page to a PDF document using PDFsharp library

I am trying to merge PDF documents and add extra pages to some of them. 我正在尝试合并PDF文档,并向其中一些添加额外的页面。 The merge part is working fine and now I am trying to figure out how to add an extra page by passing a link to the preexisting PDF page. 合并部分工作正常,现在我试图通过将链接传递到预先存在的PDF页面来弄清楚如何添加额外的页面。 How can I pass a link to a PDF page to targetDoc.AddPage(LINK)? 如何将指向PDF页面的链接传递给targetDoc.AddPage(LINK)?

    public static void MergePDFs(string targetPath, DataTable pdfs)
    {
        try
        {
            using (PdfSharp.Pdf.PdfDocument targetDoc = new PdfSharp.Pdf.PdfDocument())
            {
                foreach (DataRow pdf in pdfs.Rows)
                {
                    using (PdfSharp.Pdf.PdfDocument pdfDoc = PdfSharp.Pdf.IO.PdfReader.Open(pdf["link"].ToString(), PdfDocumentOpenMode.Import))
                    {
                        for (int i = 0; i < pdfDoc.PageCount; i++)
                        {
                            targetDoc.AddPage(pdfDoc.Pages[i]);
                        }
                    }
                }
                targetDoc.Save(targetPath);
            }
        }
        catch(Exception ex)
        {
            Console.Write(ex);
        }
    }

Stamping method 冲压方式

using (Stream pdfStream = new FileStream(sourceFileName, FileMode.Open))
{
using (Stream newpdfStream = new FileStream(newFileNameWithPath, FileMode.Create, FileAccess.ReadWrite))
{
    iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(pdfStream);
    PdfStamper pdfStamper = new PdfStamper(pdfReader, newpdfStream);
    PdfContentByte pdfContentByte = pdfStamper.GetOverContent(pageNumber);
    BaseFont baseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
    pdfContentByte.SetColorFill(BaseColor.RED);
    pdfContentByte.SetFontAndSize(baseFont, 12);
    pdfContentByte.BeginText();
    pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, inputText, Convert.ToInt32(xCoordinate), Convert.ToInt32(yCoordinate), 0);
    pdfContentByte.EndText();
    pdfStamper.Close();
}

} }

To create a new, empty page call AddPage() without parameters. 若要创建一个没有参数的新的空页面,请调用AddPage()

targetDoc.AddPage();

You might need Clone() to create multiple copies of an existing imported page (also add (PdfPage) ): 您可能需要Clone()创建一个现有导入页面的多个副本(也要添加(PdfPage) ):

targetDoc.AddPage((PdfPage)pdfDoc.Pages[i].Clone());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM