Java 类com.itextpdf.text.pdf.PdfCopy 实例源码

项目:testarea-itext5    文件:SplitSmart.java   
public List<byte[]> split(byte[] input) throws IOException, DocumentException {
    PdfReader pdfReader = new PdfReader(input);
    List<byte[]> pdfFiles = new ArrayList<>();
    int pageCount = pdfReader.getNumberOfPages();
    int pageIndex = 0;
    while (++pageIndex <= pageCount) {
        Document document = new Document(pdfReader.getPageSizeWithRotation(pageIndex));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PdfCopy pdfCopy = new PdfSmartCopy(document, byteArrayOutputStream);
        pdfCopy.setFullCompression();
        PdfImportedPage pdfImportedPage = pdfCopy.getImportedPage(pdfReader, pageIndex);
        document.open();
        pdfCopy.addPage(pdfImportedPage);
        document.close();
        pdfCopy.close();
        pdfFiles.add(byteArrayOutputStream.toByteArray());
    }
    return pdfFiles;
}
项目:testarea-itext5    文件:CopyForm.java   
/**
 * <a href="http://stackoverflow.com/questions/32710839/itextsharp-pdfcopy-makes-read-only-fields-editable">
 * iTextSharp PdfCopy makes read-only fields editable
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/nhy7av9b37uwowl/in1.pdf?dl=0">
 * in1.pdf
 * </a>
 * <p>
 * Indeed, the issue can be reproduced. A possible explanation in a SO answer.
 * </p> 
 */
@Test
public void testCopyReadOnlyFields() throws IOException, DocumentException
{
    Document document = new Document();

    try (   OutputStream fileStream = new FileOutputStream(new File(RESULT_FOLDER, "in1Copy.pdf"));
            InputStream resource = getClass().getResourceAsStream("in1.pdf")    )
    {
        PdfCopy copier = new PdfCopy(document, fileStream);
        PdfReader reader = new PdfReader(resource);

        copier.setMergeFields();
        document.open();
        copier.addDocument(reader);
        copier.addJavaScript(reader.getJavaScript());
        document.close();
    }
}
项目:AvoinApotti    文件:CatsReferralReportBuilder.java   
public void add(byte[] pdfByteArray)
{
    try
    {
        PdfReader reader = new PdfReader(pdfByteArray);
        int numberOfPages = reader.getNumberOfPages();

        if (this.document == null)
        {
            this.document = new Document(reader.getPageSizeWithRotation(1));
            this.writer = new PdfCopy(this.document, this.getOutputStream());
            this.document.open();
        }
        PdfImportedPage page;
        for (int i = 0; i < numberOfPages;)
        {
            ++i;
            page = this.writer.getImportedPage(reader, i);
            this.writer.addPage(page);
        }
        PRAcroForm acroForm = reader.getAcroForm();
        if (acroForm != null)
        {
            this.writer.copyAcroForm(reader);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
项目:testarea-itext5    文件:SplitIntoHalfPages.java   
/**
 * This methods creates a copy of the source document containing each page twice,
 * once with the cropbox limited to the left half page, once to the right one.
 */
void splitIntoHalfPages(InputStream source, File target) throws IOException, DocumentException
{
    final PdfReader reader = new PdfReader(source);

    try (   OutputStream targetStream = new FileOutputStream(target)    )
    {
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, targetStream);
        document.open();

        for (int page = 1; page <= reader.getNumberOfPages(); page++)
        {
            PdfDictionary pageN = reader.getPageN(page);
            Rectangle cropBox = reader.getCropBox(page);
            PdfArray leftBox = new PdfArray(new float[]{cropBox.getLeft(), cropBox.getBottom(), (cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getTop()});
            PdfArray rightBox = new PdfArray(new float[]{(cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getBottom(), cropBox.getRight(), cropBox.getTop()});

            PdfImportedPage importedPage = copy.getImportedPage(reader, page);
            pageN.put(PdfName.CROPBOX, leftBox);
            copy.addPage(importedPage);
            pageN.put(PdfName.CROPBOX, rightBox);
            copy.addPage(importedPage);
        }

        document.close();
    }
    finally
    {
        reader.close();
    }
}
项目:testarea-itext5    文件:SmartMerging.java   
public static byte[] ExtractPages(String pdfDocument, int startPage, int endPage) throws IOException, DocumentException
{
    try (InputStream pdfDocumentStream = SmartMerging.class.getResourceAsStream(pdfDocument))
    {
        PdfReader reader = new PdfReader(pdfDocumentStream);
        int numberOfPages = reader.getNumberOfPages();
        int endPageResolved = endPage > 0 ? endPage : numberOfPages;
        if (startPage > numberOfPages || endPageResolved > numberOfPages)
            System.err.printf("Error: page indices (%s, %s) out of bounds. Document has {2} pages.", startPage, endPageResolved, numberOfPages);

        byte[] outputDocument;
        try (ByteArrayOutputStream msOut = new ByteArrayOutputStream())
        {
            Document doc = new Document();
            PdfCopy pdfCopyProvider = new PdfCopy(doc, msOut);
            doc.open();
            for (int i = startPage; i <= endPageResolved; i++)
            {
                PdfImportedPage page = pdfCopyProvider.getImportedPage(reader, i);
                pdfCopyProvider.addPage(page);
            }
            doc.close();
            reader.close();
            outputDocument = msOut.toByteArray();
        }

        return outputDocument;
    }
}
项目:openMAXIMS    文件:CatsReferralReportBuilder.java   
public void add(byte[] pdfByteArray)
{
    try
    {
        PdfReader reader = new PdfReader(pdfByteArray);
        int numberOfPages = reader.getNumberOfPages();

        if (this.document == null)
        {
            this.document = new Document(reader.getPageSizeWithRotation(1));
            this.writer = new PdfCopy(this.document, this.getOutputStream());
            this.document.open();
        }
        PdfImportedPage page;
        for (int i = 0; i < numberOfPages;)
        {
            ++i;
            page = this.writer.getImportedPage(reader, i);
            this.writer.addPage(page);
        }
        PRAcroForm acroForm = reader.getAcroForm();
        if (acroForm != null)
        {
            this.writer.copyAcroForm(reader);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
项目:openMAXIMS    文件:CatsReferralReportBuilder.java   
public void add(byte[] pdfByteArray)
{
    try
    {
        PdfReader reader = new PdfReader(pdfByteArray);
        int numberOfPages = reader.getNumberOfPages();

        if (this.document == null)
        {
            this.document = new Document(reader.getPageSizeWithRotation(1));
            this.writer = new PdfCopy(this.document, this.getOutputStream());
            this.document.open();
        }
        PdfImportedPage page;
        for (int i = 0; i < numberOfPages;)
        {
            ++i;
            page = this.writer.getImportedPage(reader, i);
            this.writer.addPage(page);
        }
        PRAcroForm acroForm = reader.getAcroForm();
        if (acroForm != null)
        {
            this.writer.copyAcroForm(reader);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
项目:testarea-itext5    文件:StampHeader.java   
/**
    * <a href="http://stackoverflow.com/questions/29977927/table-header-in-pdf-getting-displayed-using-itextpdf5-1-1-but-not-in-itextpdf5-5">
    * table header in pdf getting displayed using itextpdf5.1.1 but not in itextpdf5.5.3
    * </a>
    * <p>
    * Indeed, the code as presented by the OP does not show the header table. This makes sense, though:
    * </p>
    * <p>
    * The OP has cells with default padding (i.e. 2) and height 10, and he tries to insert text at height 7.
    * But 2 (top margin) + 7 (text height) + 2 (bottom margin) = 11, i.e. more than fits into the cell height 10.
    * Thus, the text does not fit and is not displayed.
    * </p>
    * <p>
    * You can fix this by either
    * <ul>
    * <li>using a smaller font, e.g. 6, or
    * <li>using a higher cell, e.g. 11, or
    * <li>using a smaller padding, e.g. 1, see below-
    * </p>
    */
@Test
public void testSandeepSinghHeaderTable() throws DocumentException, IOException
{
    byte[] strIntermediatePDFFile = createSampleDocument();
    String header1 = "Header 1";
    String header2 = "Header 2";
    String header3 = "Header 3";
    String header5 = "Header 5";


    Document document = new Document(PageSize.A4.rotate(), 20, 20, 75, 20);
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(new File(RESULT_FOLDER, "stampTableHeader.pdf")));

    document.open();
    PdfReader pdfReaderIntermediate = new PdfReader(strIntermediatePDFFile);
    int numberOfPages = pdfReaderIntermediate.getNumberOfPages();
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 7, Font.NORMAL);
    System.out.println("###### No. of Pages: " + numberOfPages);
    for (int j = 0; j < numberOfPages; )
    {
        PdfImportedPage page = copy.getImportedPage(pdfReaderIntermediate, ++j);
        PageStamp stamp = copy.createPageStamp(page);
        Phrase footer = new Phrase(String.format("%d of %d", j, numberOfPages), ffont);
        ColumnText.showTextAligned(stamp.getUnderContent(),
                                   Element.ALIGN_CENTER, footer,
                                   (document.right() - document.left()) /
                                   2 + document.leftMargin(),
                                   document.bottom() - 10, 0);
        if (j != 1)
        {
            PdfPTable headerTable = new PdfPTable(2);
            headerTable.setTotalWidth(700);
            headerTable.getDefaultCell().setFixedHeight(10);
            headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            headerTable.getDefaultCell().setPadding(1); // Added!
            headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            headerTable.addCell(new Phrase(String.format(header1), ffont));
            headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            headerTable.addCell(new Phrase(String.format(header2), ffont));
            headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            headerTable.addCell(new Phrase(String.format(header3), ffont));
            headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            headerTable.addCell(new Phrase(String.format(header5, j), ffont));
            headerTable.completeRow();
            headerTable.writeSelectedRows(0, 5, 60.5f, 550, stamp.getUnderContent());
        }

        stamp.alterContents();
        copy.addPage(page);
    }
    document.close();
}
项目:preservation-tools    文件:iTextRepairPdf.java   
/**
 * Makes a copy from each PDF-file in the folder and puts it in the same
 * folder with the prefix"Mig_iText"
 * 
 * @param takes
 *            in PdfReader and the filename as a string
 * @return: void
 * 
 */

@SuppressWarnings("rawtypes")
static void repairWithItext(PdfReader reader, File filename) throws DocumentException, IOException {

    Map<String, String> info = reader.getInfo();
    Document document = new Document();

    String filenameStr = filename.getName();

    PdfCopy copy = new PdfCopy(document, new FileOutputStream(examinedFolder + "//" + "Mig_iText" + filenameStr));

    int pdfVersion = filetools.pdf.PdfAnalysis.getPdfVersion(filename.toString());

    //TODO: But all the output PDF is PDF 1.4
    switch (pdfVersion) {
    case 2:
        copy.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
        break;
    case 3:
        copy.setPdfVersion(PdfWriter.PDF_VERSION_1_3);
        break;
    case 4:
        copy.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
        break;
    case 5:
        copy.setPdfVersion(PdfWriter.PDF_VERSION_1_5);
        break;
    case 6:
        copy.setPdfVersion(PdfWriter.PDF_VERSION_1_6);
        break;
    case 7:
        copy.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
        break;
    }

    // TODO: there is a way to get all the metadata as described in one of
    // Bruno's books
    if (info.get("Title") != null)
        document.addTitle((String) info.get("Title"));
    if (info.get("Author") != null)
        document.addAuthor((String) info.get("Author"));
    if (info.get("Keywords") != null)
        document.addKeywords((String) info.get("Keywords"));
    // TODO: Is this the right Keyword?
    if (info.get("Date") != null)
        document.addKeywords((String) info.get("Date"));
    copy.createXmpMetadata();
    document.open();
    int n = reader.getNumberOfPages();
    for (int i = 0; i < n;) {
        copy.addPage(copy.getImportedPage(reader, ++i));
    }
    copy.freeReader(reader);
    document.close();
}
项目:sldownloader    文件:Pdf.java   
public void mergePdfs() throws DocumentException, IOException {
    String title = book.getPdfTitle() + ".pdf";
    File saveFile = new File(saveFolder, title);

    int count = 1;
    while (saveFile.exists()) {
        title = book.getPdfTitle() + "_" + count++ + ".pdf";
        saveFile = new File(saveFolder, title);
    }
    book.setInfo("saveFile", saveFile.toString());

    Document document = new Document();
    PdfCopy destPdf = new PdfCopy(document, new FileOutputStream(saveFile));
    document.open();
    PdfReader reader;
    int page_offset = 0;
    int n;
    ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<HashMap<String, Object>>();
    List<HashMap<String, Object>> tmp;

    count = 1;
    System.out.println("Start mergin\u2026");
    for (File srcPdf : src) {

        if (Thread.interrupted()) {
            return;
        }

        System.out.print(":: " + count++ + "/" + src.size());
        reader = new PdfReader(srcPdf.toString());

        tmp = SimpleBookmark.getBookmark(reader);
        if (tmp != null) {
            SimpleBookmark.shiftPageNumbers(tmp, page_offset, null);
            bookmarks.addAll(tmp);
        }

        n = reader.getNumberOfPages();
        page_offset += n;
        for (int page = 0; page < n;) {
            destPdf.addPage(destPdf.getImportedPage(reader, ++page));
        }
        destPdf.freeReader(reader);
        reader.close();
        System.out.println(" succeed.");
    }
    if (!bookmarks.isEmpty()) {
        destPdf.setOutlines(bookmarks);
    }

    if (book.getInfo("author") != null)
        document.addAuthor(book.getInfo("author"));
    if (book.getInfo("title") != null)
        document.addTitle(book.getInfo("title"));
    if (book.getInfo("subtitle") != null)
        document.addSubject(book.getInfo("subtitle"));
    document.close();

    System.out.println("Merge complete. Saved to " + saveFile);
}