这就是我过去的做法。您需要为 PDF 编写器使用新的流,并将原始 PDF 内容添加到新文档中。这可能不是执行此操作的最佳或最有效的方法,这正是我发现的有效方法。
这适用于来自 a 的原始 PDF Stream
,并将合并的输出生成为 another Stream
,但是您应该能够根据您的需要对其进行调整。
var originalPdfStream = GetOriginalPdfStream();
var pdfDocument = Document();
var finalPdfStream = new MemoryStream();
var pdfWriter = PdfWriter.GetInstance(pdfDocument, finalPdfStream);
pdfDocument.Open();
// Add the originalPdfStream into the pdfDocument
var originalPdfReader = new PdfReader(originalPdfStream);
AddPdf(document, writer, reader);
// Code to add other items to the pdfDocument.
pdfWriter.CloseStream = false;
pdfDocument.Close();
finalPdfStream.Position = 0;
return finalPdfStream;
然后,以下方法将您的文档和作者以及读者带到您要添加的文档。
/// <summary>
/// Merge a PDF file into a PDF document.
/// </summary>
/// <param name="document">The PDF document.</param>
/// <param name="writer">The PDF writer.</param>
/// <param name="reader">A PDF reader.</param>
private static void AddPdf(Document document, PdfWriter writer, PdfReader reader)
{
if (document == null) throw new ArgumentNullException("document");
if (writer == null) throw new ArgumentNullException("writer");
if (reader == null) throw new ArgumentNullException("reader");
var numberOfPages = reader.NumberOfPages;
var originalPageSize = document.PageSize;
// Iterate through all pages
for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
{
// Determine page size for the current page
document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex));
// Create page
document.NewPage();
var importedPage = writer.GetImportedPage(reader, currentPageIndex);
// Determine page orientation and add page.
var pageRotation = reader.GetPageRotation(currentPageIndex);
var pageWidth = reader.GetPageSizeWithRotation(currentPageIndex).Width;
var pageHeight = reader.GetPageSizeWithRotation(currentPageIndex).Height;
switch (pageRotation)
{
case 0:
writer.DirectContent.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
break;
case 90:
writer.DirectContent.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, pageHeight);
break;
case 180:
writer.DirectContent.AddTemplate(
importedPage, -1f, 0, 0, -1f, pageWidth, pageHeight);
break;
case 270:
writer.DirectContent.AddTemplate(importedPage, 0, 1f, -1f, 0, pageWidth, 0);
break;
default:
throw new Exception("Unexpected page rotation: [{0}].", pageRotation);
}
}
document.SetPageSize(originalPageSize);
}