Copy from 1 pdf to another by creating images of all pages

Hi

I want to copy images of all pages from 1 pdf to another, Can you provide some code sample for that

@hardeep17

Do you want to extract images and place it on same location in another PDF document? It would be helpful if you can please share a sample PDF document and expected output. We will test the scenario in our environment and address it accordingly.

No I do not want to extract images. I want to append few pages of one pdf to another pdf file. I am using
something like this.

toDoc.getPages().add(fromDoc.getPages().get_Item(page, 1));

But for some reason if the above method fails, I want to have a fallback saying get a image of the page (kind of screenshot) and append to other pdf. Here is my code snippet

                File tempFile = File.createTempFile("aaa", Constants.FileType.PNG.getExtension());
                OutputStream imageStream = new FileOutputStream(tempFile.getAbsolutePath());
                // Create Resolution object
                Resolution resolution = new Resolution((int) (oldPage.getPageInfo().getWidth() * 
               oldPage.getPageInfo().getHeight()));
                PngDevice pngDevice = new PngDevice(resolution);
                // Convert a particular page (Page 1) and save the image to stream
                pngDevice.process(oldPage, tempFile.getAbsolutePath());
                // Close the stream
                imageStream.close();

                FileInputStream fs = new java.io.FileInputStream(tempFile.getAbsolutePath());
                // Set margins so image will fit, etc.
                newPage.getPageInfo().getMargin().setBottom(0);
                newPage.getPageInfo().getMargin().setTop(0);
                newPage.getPageInfo().getMargin().setLeft(0);
                newPage.getPageInfo().getMargin().setRight(0);
               Image image1 = new Image();
              newPage.getParagraphs().add(image1);
               image1.setImageStream(fs);

Is this the correct way to do? Also, how can i set resolution of image to the from Document resolution?

The above snippet works but takes a long time to generate images and append. I was wondering if there is any faster and better way

@hardeep17

The code snippet you have shared seems fine and should not create any issue. However, you first approach of adding Page into PageCollection of PDF is recommended one and would you kindly explain why it is failing?

Regarding your second method and delay in processing, it may depend upon the structure and complexity of PDF documents being processed. Would you please share your environment details like OS version and details, installed memory and application type with us. Also, please share your sample PDF documents with us. It would really help us testing the scenario in our environment and address it accordingly.