【问题标题】:How to remove images from pdf using PDFSharp?如何使用 PDFSharp 从 pdf 中删除图像?
【发布时间】:2016-10-24 08:35:55
【问题描述】:

如何使用 PDFSharp 从现有 pdf 中删除图像(全部)?

我试过这段代码:

public static PdfDocument RemoveImages(PdfDocument pdf)
{
    foreach (PdfPage page in pdf.Pages)
    {
        PdfDictionary resource = page.Elements.GetDictionary("/Resources");
        if (resource != null)
        {
            PdfDictionary objects = resource.Elements.GetDictionary("/XObject");
            if (objects != null)
            {
                foreach (string itemKey in objects.Elements.Keys)
                {
                    PdfItem item = objects.Elements[itemKey];
                    PdfReference reference = item as PdfReference;                          
                    if (reference != null)
                    {
                        PdfDictionary xObject = reference.Value as PdfDictionary;
                        if (xObject != null && xObject.Elements.GetString("/Subtype") == "/Image")
                        {
                            pdf.Internals.RemoveObject((PdfObject)reference.Value); // remove image from internal document table
                            objects.Elements.Remove(itemKey); // remove image from page resource
                        }
                    }
                }
            }
        }
    }

    return pdf;
}

但是在 Acrobat Reader 中打开该文件时,此代码会导致 pdf 损坏...

如何使用 PDFSharp 从现有 pdf 中删除图像而不会损坏?

提前致谢!

【问题讨论】:

    标签: c# pdfsharp


    【解决方案1】:

    您删除了图像,但不更改绘制图像的页面的内容。 Adobe Reader 尝试绘制不再存在的图像。 这就是您的文件损坏的原因。

    可能的解决方案(只是猜测,不是我的专业领域):

    • 将图片替换为透明图片,让页面绘制透明图片。
    • 解析页面内容并删除所有绘制已删除图像的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 2011-09-21
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      相关资源
      最近更新 更多