How to reorder the pages of a PDF file?

后端 未结 2 1895
感情败类
感情败类 2021-01-23 12:11

I am generating Table of Contents at last,I want to move Table of Contents at Beginning. Suppose that I have 16 pages in my PDF and that the TOC starts from page 13 and ends on

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 12:12

    You can select the pages readed by PdfReader:

    PdfReader sourcePDFReader = new PdfReader(RESULT1);
    reader.selectPages("1-13");
    

    Then you can use PdfStamper or PdfCopy to assemble then in order. Please refer to:

    Itext Documentation, Related question

    Edit: This is a piece of code i use to put a list of pdf together, maybe it's helpful to you. (You could read pages 15-16, save to pdf and then repeat with pages 1-13. Then combine the two resulting pdfs)

    private byte[] combinePdf(List archivos) throws DocumentException,
            IOException {
        ByteArrayOutputStream osPdf = new ByteArrayOutputStream();
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        PdfWriter writer = PdfWriter.getInstance(document, osPdf);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
    
        for (byte[] in : archivos) {
            PdfReader reader = new PdfReader(in);
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                document.newPage();
                PdfImportedPage page = writer.getImportedPage(reader, i);
                cb.addTemplate(page, 0, 0);
            }
        }
        osPdf.flush();
        document.close();
    
        return osPdf.toByteArray();
    }
    

    Edit 2: as Bruno posted, this is a bad solution because all the pdf links are lost using the document/ pdfWritter combination.

提交回复
热议问题