如何在不丢失页面大小和元信息的情况下将pdf复制到另一个?

时间:2014-09-16 14:58:05

标签: java itext

我的目标是取出pdf的第二页,并将其他pdf的内容放入其中。

我已经看了其他答案,我已经编写了删除模板页面的代码(第2页)。但是,当我将其他页面复制到第一套新书时,我会得到各种疯狂的裁剪。它没有出来。我尝试使用setpagesize选项,但它似乎仍然无法正常工作。

我是以错误的方式解决这个问题吗?

package com.protocase.itexthelper;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author davidh
 */
public class ITextHelper {

    public static void deletePage(String fileToPrune, int pageToDelete, String newFilePath) {

        PdfReader pdfReader = null;
        try {
            pdfReader = new PdfReader(fileToPrune);
        } catch (IOException ex) {
            Logger.getLogger(ITextHelper.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (pdfReader != null) {
            List<Integer> pagesToKeep = new ArrayList<Integer>();

            //pdfReader.getPages
            for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
                if (i != pageToDelete) {
                    pagesToKeep.add(i);
                }
            }
            pdfReader.selectPages(pagesToKeep);
        }

        PdfStamper pdfStamper = null;
        try {
            pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(newFilePath));

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ITextHelper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DocumentException | IOException ex) {
            Logger.getLogger(ITextHelper.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (pdfStamper != null) {
                try {
                    pdfStamper.close();
                } catch (DocumentException | IOException ex) {
                    Logger.getLogger(ITextHelper.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (pdfReader != null) {
                pdfReader.close();
            }
        }
    }


    // -- begin-
    public static void main(String[] args) {
        String fileToAddTo = "src/com/protocase/itexthelper/examplepdf/BUILD_SHEETS_O4_4USS Rev5.pdf";
        String fileWithPageRemoved = "src/com/protocase/itexthelper/examplepdf/BUILD_SHEETS_O4_4USS Rev5-no page 2.pdf";
        String fileToAppend = "src/com/protocase/itexthelper/examplepdf/example_component_list.pdf";
        String testFile = "src/com/protocase/itexthelper/examplepdf/testfile.pdf";
        deletePage(fileToAddTo, 2, testFile);
        addPDFToPDF(fileWithPageRemoved, fileToAppend, testFile, 2);
    }

    /**
     * @param originalFilePath Merge multiple pdf into one pdf
     * @param fileToInsertPath
     *
     * @param list of pdf input stream
     * @param location where you want to insert the page
     * @param outputLocation output stream
     * @throws DocumentException
     * @throws IOException
     */
    public static void addPDFToPDF(String originalFilePath, String fileToInsertPath, String outputLocation, int location) {
        OutputStream out = null;
        try {
            out = new FileOutputStream(new File(outputLocation));
        } catch (FileNotFoundException ex) {
            System.out.println("ITextHelper.addPDFToPDF(): can't find output file location: "+ex);
        }
        Document document = new Document();
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document, out);
        } catch (DocumentException ex) {
            System.out.println("ITextHelper.addPDFToPDF(): issue getting writer: "+ex);
        }

        document.open();
        if (writer != null) {

            PdfContentByte cb = writer.getDirectContent();

            PdfReader originalFileReader = null;
            try {
                originalFileReader = new PdfReader(originalFilePath);
            } catch (IOException ex) {
                System.out.println("ITextHelper.addPDFToPDF(): can't read original file: " + ex);
            }
            PdfReader fileToAddReader = null;
            try {
                fileToAddReader = new PdfReader(fileToInsertPath);
            } catch (IOException ex) {
                System.out.println("ITextHelper.addPDFToPDF(): can't read fileToInsert: " + ex);
            }

            if (fileToAddReader != null && originalFileReader != null) {
                for (int i = 1; i <= originalFileReader.getNumberOfPages(); i++) {
                    if (i == location) {
                        for (int j = 1; j <= fileToAddReader.getNumberOfPages(); j++) {
                            document.newPage();

                            document.setPageSize(fileToAddReader.getPageSize(j));
                            //import the page from source pdf
                            PdfImportedPage page = writer.getImportedPage(fileToAddReader, j);
                            //add the page to the destination pdf
                            cb.addTemplate(page, 0, 0);
                        }
                    }
                    document.newPage();
                    document.setPageSize(originalFileReader.getPageSize(i));
                    PdfImportedPage page = writer.getImportedPage(originalFileReader, i);
                    cb.addTemplate(page, 0, 0);
                }
            }
        }
        closeOutputStream(out, document);
    }
    // -- end

    private static void closeOutputStream(OutputStream out, Document document) {
        if (out != null) {
            try {
                out.flush();
            } catch (IOException ex) {
                System.out.println("ITextHelper.closeOutputStream(): can't flush outstream: " + ex);
            }
            document.close();
            try {
                out.close();
            } catch (IOException ex) {
                System.out.println("can't close outstream: " + ex);
            }
        }
    }

}

1 个答案:

答案 0 :(得分:2)

所以,我看了一下Bruno Lowagie的书,然后来看看这段代码。实际上很完美。

    /**
     * @param originalFilePath PDF to append to
     * @param fileToInsertPath PDF to append
     * @param outputFile Where to save to
     * @param location where you want to insert the page
     */
    public static void mergePDFs(String originalFilePath, String fileToInsertPath, String outputFile, int location) {

        PdfReader originalFileReader = null;
        try {
            originalFileReader = new PdfReader(originalFilePath);
        } catch (IOException ex) {
            System.out.println("ITextHelper.addPDFToPDF(): can't read original file: " + ex);
        }
        PdfReader fileToAddReader = null;
        try {
            fileToAddReader = new PdfReader(fileToInsertPath);
        } catch (IOException ex) {
            System.out.println("ITextHelper.addPDFToPDF(): can't read fileToInsert: " + ex);
        }

        if (originalFileReader != null && fileToAddReader != null) {

            // -- Copy
            int numberOfOriginalPages = originalFileReader.getNumberOfPages();
            Document document = new Document();
            PdfCopy copy = null;
            try {
                copy = new PdfCopy(document, new FileOutputStream(outputFile));
                document.open();

                for (int i = 1; i <= numberOfOriginalPages; i++) {
                    if (i == location) {
                        for (int j = 1; j <= fileToAddReader.getNumberOfPages(); j++) {
                            copy.addPage(copy.getImportedPage(fileToAddReader, j));
                        }
                    }
                    copy.addPage(copy.getImportedPage(originalFileReader, i));

                }
                document.close();
            } catch (DocumentException | FileNotFoundException ex) {
                System.out.println("ITextHelper.addPDFToPDF(): can't read output location: " + ex);
            } catch (IOException ex) {
                Logger.getLogger(ITextHelper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }