简体   繁体   中英

How to remove images from pdf using PDFSharp?

How can I remove images (all) from existing pdf using PDFSharp?

I tried this code:

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;
}

But this code provide pdf curruption when open that file in Acrobat Reader...

How can I remove images from existing pdf using PDFSharp without curruption?

Thanks in advance!

You remove the images, but do not change the contents of the pages where the images are drawn. Adobe Reader tries to draw an image that is no longer there. That's why your files are corrupt.

Possible solutions (just guessing, not my area of expertise):

  • Replace the images with transparent images, let the pages draw transparent images.
  • Parse the contents of the pages and remove all code that draws removed images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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