Copy image from a document to another with PDFtron

101 Views Asked by At

In the following sections I describe my goal, my issue and my question:

Goal

I have some custom tickets for attractions in PDF format and I'd like to remove certain images from the tickets. The way I do this is I read everything from a PDF ticket, write it to a new document, and skip some of the elements I already read.

Issue and code

When I read (image)elements, read its' height and width and write it to a new document, the resulting image is way smaller than the original one. I removed a lot of things from the code, for example: the write of text and other kind of elements to new document, disposing, etc.

using (PDFDoc inputDoc = new PDFDoc(_inputFilePath))
using (ElementReader reader = new ElementReader())
{
    ElementWriter writer = new ElementWriter();
    ElementReader reader = new ElementReader(); 
    PageIterator itr = doc.GetPageIterator();

    while (itr.HasNext())
    {       
        Page page = itr.Current();      
        reader.Begin(page);
        writer.Begin(page, ElementWriter.WriteMode.e_replacement, false, true, page.GetResourceDict());     
        
        Element element;
        // Read elements here
        while ((element = reader.Next()) != null)
        {
            // skip certain elements here, but leave the images below
            if (shouldSkipElement(element, writer, doc))
            {
                continue;
            }
            var elemType = element.GetType();
            if(elemType == Element.Type.e_image || elemType == Element.Type.e_inline_image)
            {           
                Image imageElement = new Image(element.GetXObject());
                var height = imageElement.GetImageHeight(); 
                var width = imageElement.GetImageWidth(); 
                var builder = new ElementBuilder();
                Element? outoutImageElem;               
                
                // Write elements here
                // following row creates too small image
                // height is 735 here
                // width is 1155 here
                outoutImageElem = builder.CreateImage(imageElement, 0, 0, height, width);
                
                // following row creates almost the same size of image  
                // outoutImageElem = builder.CreateImage(imageElement, 0, 0, 1570, 1000);
                writer.WritePlacedElement(outoutImageElem);             
            }          
        }

        itr.Next();     
        // Dispose and save etc.
    }
}

Original PDF

enter image description here

Result PDF(copied only one, the orange image at the moment)

enter image description here

Question

Does anyone know a solution, how should I copy images from one document to another using Apryse PDFTron SDK, keeping the original resolution? What do I do wrong here?

0

There are 0 best solutions below