c# - 使用 iTextSharp 读取/修改 PDF 元数据,而无需在 pdf 属性上向用户显示任何数据

标签 c# wpf pdf visual-studio-2012 itext

我正在尝试使用 iTextSharp 读取/修改 PDF 元数据。不向用户显示任何信息。我完成了以下代码:

iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 20f, 20f, 20f, 20f);
using (MemoryStream memStream = new MemoryStream())
{
    using (PdfWriter wri = PdfWriter.GetInstance(document, memStream))
    {
        document.Open(); document.AddSubject("Test"); document.Close();
    }
}

我将不胜感激任何指向解决方案的指示。

最佳答案

您使用的代码片段是关于将元数据添加到从头开始创建的 PDF 文档。您要求从现有 PDF 文档中读取元数据。请查看 iText 网站上的文档,更具体地说是问答条目 How to add / delete / retrieve information from a PDF using a custom property?

诚然,该问题的答案中使用的代码是用 Java 编写的,但将其移植到 C# 相当容易。这是另一个片段:

public byte[] ManipulatePdf(byte[] src) {
    PdfReader reader = new PdfReader(src);
    using (MemoryStream ms = new MemoryStream()) {
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
            Dictionary<String, String> info = reader.Info;
            info["Title"] = "Hello World stamped";
            info["Subject"] = "Hello World with changed metadata";
            info["Keywords"] = "iText in Action, PdfStamper";
            info["Creator"] = "Silly standalone example";
            info["Author"] = "Also Bruno Lowagie";
            stamper.MoreInfo = info;
        }
        return ms.ToArray();
    }
}

您可以通过 PdfReader 从现有 PDF 中检索元数据。您会得到一个 Dictionary,其中的键与 ISO-32000-1 中信息字典的键相对应。如果您想更改元数据,可以使用 PdfStamper 进行。

此功能将读取和调整 Info 字典(这是您在代码片段中提到的)。 PDF 还可以包含 XMP 元数据。

XMP 元数据可以这样读取:

public string ReadXmpMetadata(byte[] src) {
    PdfReader reader = new PdfReader(src);
    byte[] b = reader.Metadata;
    return Encoding.UTF8.GetString(b, 0, b.Length);
}  

您可以像这样更改 XMP 元数据:

public byte[] ManipulatePdf(byte[] src) {
    PdfReader reader = new PdfReader(src);
    using (MemoryStream ms = new MemoryStream()) {
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
            Dictionary<String, String> info = reader.Info;
            using (MemoryStream msXmp = new MemoryStream()) {
                XmpWriter xmp = new XmpWriter(msXmp, info);
                xmp.Close();
                stamper.XmpMetadata = msXmp.ToArray();      
            }
        }
        return ms.ToArray();
    }
}

我假设您知道信息字典和 PDF 中的 XMP 元数据流之间的区别。

关于c# - 使用 iTextSharp 读取/修改 PDF 元数据,而无需在 pdf 属性上向用户显示任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33950199/

相关文章:

c# - Asp.NET MVC 应用程序中的静态类

C#/WPF 应用程序抛出 ObjectDisposedException;为什么我无法捕获或获取堆栈跟踪?

c# - WPF:带 Canvas 的图像

c# - 更改 TextBox 的标准行为?

c# - 了解数据绑定(bind)

python-3.x - 无法在谷歌云功能中使用 Wand/ImageMagick 加载 PDF

php - wkhtmltopdf 从文件随机空框生成 PDF

android - 如何在 Android 中以原始格式创建 PDF 文件

c# - Windows.Forms SplitContainer.SplitterWidth 不会在运行时保持设置

c# - 在 ASP.NET Core 中使用 WebGrid