繁体   English   中英

如何使用PDFSharp从pdf删除图像?

[英]How to remove images from pdf using PDFSharp?

如何使用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中删除图像而不会造成损坏?

提前致谢!

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM