使用iTextSharp在现有pdf中添加新页面

本文关键字:添加 新页面 pdf iTextSharp 使用 | 更新日期: 2023-09-27 17:59:26

我有一个1页的pdf文件。现在我想再添加两页,其中包含一些数据或图像。我试过了,但它没有添加新页面:

private void addPage()
   {
     Document document = new Document();
     writer = PdfWriter
        .GetInstance(document, new FileStream(outputFileName, FileMode.Create));
        document.Open();
        PdfContentByte cb = writer.DirectContent;

     for (int pageNumber = 1;pageNumber < reader.NumberOfPages + 2;pageNumber++)
        {
            document.SetPageSize(reader.GetPageSizeWithRotation(1));
            document.NewPage();
            if (pageNumber == 1)
            {
                Chunk fileRef = new Chunk(" ");
                fileRef.SetLocalDestination(newPdf);
                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);
            }
        }
        document.NewPage();
        Paragraph paragraph = new Paragraph();
        iTextSharp.text.Font titleFont =
            new iTextSharp.text.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 iTextSharp.text.Font(
                iTextSharp.text.Font.FontFamily.HELVETICA
                , 12
                , iTextSharp.text.Font.NORMAL
                , BaseColor.BLACK
            );
        Chunk textChunk = new Chunk("", textFont);
        paragraph.Add(textChunk);
        document.Add(paragraph);
        }
        document.Close();
  }

使用iTextSharp在现有pdf中添加新页面

尝试将页面添加到PDF文档中:

PdfDocument pdfDoc = new PdfDocument(); // create document
PdfPage pdfPage = new PdfPage(); // create page 
pdfPage.Size = PageSize.Letter; // set page size
pdfDoc.Pages.Add(pdfPage); // add page to document