将现有 PdfDocument 保存到文件

Save existing PdfDocument to file

我目前正在尝试拆分一个 PDF 文件,然后将每个 PdfDocument 保存到一个新文件中。问题是我找不到任何方法将新的 PdfWriter 附加到现有的 PdfDocument。这是我目前用来打开和拆分 PDF 文件的代码(只是一个模型代码示例):

IList<int> splitByPage = new List<int>() { 1,2,3};
PdfDocument pdfDoc = new PdfDocument(new PdfReader(@"C:\temp\test.pdf"));
PdfSplitter splitter = new PdfSplitter(pdfDoc);
IList<PdfDocument> splittedDocuments = splitter.SplitByPageNumbers(splitByPage);

这是有效的,我有一组 PdfDocument 对象。现在我想将它们保存到新文件中。我在 java 中找到了一个解决方案,可以根据给定的 DocumentOutputStream 创建 PdfWriter 的新实例,但在 .net 中我没有找到相当于这个。感谢您的帮助!

长话短说,您需要扩展 GetNextPdfWriter 方法上的 PdfSplitter class handles the documents, by creating a new PdfWriter 实例。

public static readonly String DEST = "splitDocument1_{0}.pdf";


public void Split()
{
    IList<int> splitByPage = new List<int>() {1, 2, 3};
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(@"C:\temp\hello.pdf"));
    PdfSplitter splitter = new PdfSplitter(pdfDoc);
    IList<PdfDocument> splittedDocuments = new CustomPdfSplitter(pdfDoc, DEST).SplitByPageNumbers(splitByPage);

    foreach (PdfDocument doc in splittedDocuments)
    {
        doc.Close();
    }

    pdfDoc.Close();
}

private class CustomPdfSplitter : PdfSplitter
{
    private String dest;
    private int partNumber = 1;

    public CustomPdfSplitter(PdfDocument pdfDocument, String dest) : base(pdfDocument)
    {
        this.dest = dest;
    }

    protected override PdfWriter GetNextPdfWriter(PageRange documentPageRange)
    {
        return new PdfWriter(String.Format(dest, partNumber++));
    }
}

我无法在网上找到 GetNextPdfWriter 的文档,但这里是 source code:

/// <summary>This method is called when another split document is to be created.</summary>
/// <remarks>
/// This method is called when another split document is to be created.
/// You can override this method and return your own
/// <see cref="T:iText.Kernel.Pdf.PdfWriter" />
/// depending on your needs.
/// </remarks>
/// <param name="documentPageRange">the page range of the original document to be included in the document being created now.
/// </param>
/// <returns>the PdfWriter instance for the document which is being created.</returns>
protected internal virtual PdfWriter GetNextPdfWriter(PageRange documentPageRange)

除了 Github, I could also find an example on the Volume Counter FAQ 上的示例(第 3 个示例)。