Itext 7 - 需要 (pdfdocument.GetPage(4).GetContentBytes()) 的解决方案

Itext 7 - Need solution for (pdfdocument.GetPage(4).GetContentBytes())

我正在尝试 pdfDocument.GetPage(4).GetContentBytes() 但是得到一个错误对象引用未设置为对象的实例。 内核 extension.get[tkey, tvalue] 处的 itext 内核 但是如果我尝试 pdfDocument.GetPage(5).GetContentBytes() 它正在工作。

在评论中你说:

I am creating a pdf from Json Data , after particular point need to read a particular content in pdf

so i am using this method pdfDocument.GetPage(4).GetContentBytes() to read it but not able to read the content in page 4

据此,您尝试检索您最近在同一 PdfDocument 实例中创建的页面的内容字节。

我假设您正在使用 Document 实例创建 PDF 中的内容,该实例是使用单参数构造函数创建的:

/// <summary>
/// Creates a document from a <see cref="iText.Kernel.Pdf.PdfDocument"/>.
/// </summary>
/// <remarks>
/// Creates a document from a <see cref="iText.Kernel.Pdf.PdfDocument"/>.
/// Initializes the first page with the <see cref="iText.Kernel.Pdf.PdfDocument"/>'s
/// current default <see cref="iText.Kernel.Geom.PageSize"/>.
/// </remarks>
/// <param name="pdfDoc">the in-memory representation of the PDF document</param>
public Document(PdfDocument pdfDoc)

或双参数构造函数:

/// <summary>
/// Creates a document from a <see cref="iText.Kernel.Pdf.PdfDocument"/>
/// with a manually set <see cref="iText.Kernel.Geom.PageSize"/>.
/// </summary>
/// <param name="pdfDoc">the in-memory representation of the PDF document</param>
/// <param name="pageSize">the page size</param>
public Document(PdfDocument pdfDoc, PageSize pageSize)

不幸的是,对于您的用例,这两个构造函数都激活了 Document 代码中的优化,该代码在开始填充下一页后尽快将页面数据从内存刷新到目标输出流。 (此优化允许使用 iText 7 创建大型 PDF,同时保持较小的内存需求。)

在你的情况下,iText 似乎已经刷新了第 4 页(导致你的错误)但还没有刷新第 5 页(所以它的内容仍然可以被检索)。

如果您需要在开始将内容放入下一页后很久才访问页面,您应该改用三重参数 Document 构造函数

/// <summary>
/// Creates a document from a <see cref="iText.Kernel.Pdf.PdfDocument"/>
/// with a manually set <see cref="iText.Kernel.Geom.PageSize"/>.
/// </summary>
/// <param name="pdfDoc">the in-memory representation of the PDF document</param>
/// <param name="pageSize">the page size</param>
/// <param name="immediateFlush">
/// if true, write pages and page-related instructions to the
/// <see cref="iText.Kernel.Pdf.PdfDocument"/> as soon as possible.
/// </param>
public Document(PdfDocument pdfDoc, PageSize pageSize, bool immediateFlush)

immediateFlush 值为 false