gpt4 book ai didi

c# - 将现有的 PdfDocument 保存到文件

转载 作者:行者123 更新时间:2023-12-04 10:47:43 24 4
gpt4 key购买 nike

我目前正在尝试拆分 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中找到了一个解决方案,可以根据给定的 Document创建一个新的PdfWriter实例。和一个 OutputStream但在 .net 中我没有找到与此等效的。谢谢你的帮助!

最佳答案

长话短说,您需要扩展 PdfSplitter类通过创建一个新的 PdfWriter 来处理文档。 GetNextPdfWriter 方法上的实例。

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 上的例子,我也可以在 Volume Counter FAQ 上找到一个例子(第三个例子)。

关于c# - 将现有的 PdfDocument 保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59625711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com