Example usage for com.itextpdf.text.pdf PdfWriter getImportedPage

List of usage examples for com.itextpdf.text.pdf PdfWriter getImportedPage

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter getImportedPage.

Prototype

public PdfImportedPage getImportedPage(final PdfReader reader, final int pageNumber) 

Source Link

Document

Use this method to get a page from other PDF document.

Usage

From source file:gravabncertificado007.CarimboCertificado.java

public void aplicaCariboGedi(String BN, String caminhoarquivo)
        throws DocumentException, IOException, RuntimeException {

    PdfReader.unethicalreading = true;//from   w ww . j av  a2 s.co m
    //Cria o reader para o primeiro PDF

    PdfReader reader = new PdfReader(caminhoarquivo);
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getWidth();
    float height = psize.getHeight();

    Document document = new Document(new Rectangle(width, height));

    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-G.pdf"));

    document.open();

    int i = 0;
    BN = BN.substring(BN.length() - 13, BN.length() - 4);
    PdfContentByte cb = writer.getDirectContent();
    while (i < reader.getNumberOfPages()) {
        i++;

        document.newPage();

        PdfContentByte under = writer.getDirectContentUnder();
        PdfImportedPage page1 = writer.getImportedPage(reader, i);
        cb.addTemplate(page1, 0, i * 0.2f);

        BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 14);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "  _________________  ", width / 6, 44, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 32, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 22, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |Copia Controlada |", width / 6, 28, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 16, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 12, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |_________________|", width / 6, 14, 0);
        cb.endText();
    }

    document.close();
    writer.close();
    reader.close();

}

From source file:jasperSoft.MergePDF.java

/**
 * /*from w ww.j  ava  2  s  . co  m*/
 * @param streamOfPDFFiles
 * @param outputStream
 * @param paginate 
 */
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the outputstream
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
        // data

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                            "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:jati.GerandoArquivoCarimbado.java

public static void GerandoArquivoCarimbadoPDF(String caminhoarquivo, String BN)
        throws InvalidPdfException, IOException {
    //Copiando arquivo informado.

    try {/*  w w  w  . j a va 2  s .  c o m*/

        // Adicionado parametro para nao retornar erro quando o documento for protegido.
        PdfReader.unethicalreading = true;

        PdfWriter writer = PdfWriter.getInstance(montaraAquivo(caminhoarquivo),
                new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf"));
        // ABRE O DOCUMENTO CRIADO PARA MANUSEIO
        montaraAquivo(caminhoarquivo).open();

        //SUBSTRING RETIRA PARTE DO TEXTO ENTRE OS INDICES ESPECIFICADOS 
        //caminhoDestino RECEBE UM NOVO CAMINHO RESULTANTE DOS INDICES DE CAMINHO.LENGTH - BN.LENGTH
        // QUE FORMAM UMA NOVA STRING
        String caminhodestino = (caminhoarquivo.substring(0, caminhoarquivo.length() - BN.length()));

        File destinooriginal = new File(caminhodestino + "ORIGINAL\\");
        if (!destinooriginal.exists()) {
            destinooriginal.mkdir();
        }

        caminhodestino = (caminhodestino + "ORIGINAL\\" + BN);

        //TESTANDO NOVA FORMA DE COPIAR
        File origem = new File(caminhoarquivo);
        File destino = new File(caminhodestino);

        FileInputStream fis = new FileInputStream(origem);
        FileOutputStream fos = new FileOutputStream(destino);

        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();

        long transferFrom = outChannel.transferFrom(inChannel, 0, inChannel.size());

        fis.close();
        fos.close();
        inChannel.close();
        outChannel.close();

        // Thread.sleep(10);
        BN = BN.substring(0, BN.length() - 4);

        PdfContentByte cb = writer.getDirectContent();

        int i = 0;
        while (i < reader.getNumberOfPages()) {
            montaraAquivo(caminhodestino).newPage();

            i++;

            //PDFCONTETBYTE GERA UMA ESPECIE DE CODIGO DE BARRAS 
            PdfContentByte under = writer.getDirectContentUnder();
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 0, i * 0.2f);

            //CARIMBO DA BN
            BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            cb.beginText();
            cb.setFontAndSize(bf, 14);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 32, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 22, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 12, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0);
            cb.endText();

        }

        montaraAquivo(caminhodestino).close();
        writer.close();
        reader.close();
        origem.delete();

    } catch (IOException | DocumentException ex) {
    }

}

From source file:nz.ac.waikato.cms.doc.HyperLinkGrades.java

License:Open Source License

/**
 * Adds the index with locations to the existing PDF.
 *
 * @param locations   the locations to index
 * @param input   the input PDF/*from   w  ww  .j  av  a2 s.co m*/
 * @param output   the output PDF
 * @return      true if successfully generated
 */
public static boolean addIndex(List<Location> locations, File input, File output) {
    try {
        // copy pages, add target
        PdfReader reader = new PdfReader(input.getAbsolutePath());
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(output.getAbsolutePath()));
        document.open();
        PdfContentByte canvas = writer.getDirectContent();
        PdfImportedPage page;
        float height = 0;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            document.newPage();
            page = writer.getImportedPage(reader, i);
            canvas.addTemplate(page, 1f, 0, 0, 1, 0, 0);
            Chunk loc = new Chunk(" ");
            loc.setLocalDestination("loc" + i);
            height = page.getHeight();
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(loc), 50, height - 50, 0);
        }
        // add index
        for (int i = 0; i < locations.size(); i++) {
            Location loc = locations.get(i);
            if (i % MAX_ITEMS_PER_PAGE == 0)
                document.newPage();
            String text = loc.getID() + " " + (loc.getName() == null ? "???" : loc.getName());
            Chunk chunk = new Chunk("Page " + (loc.getPage() + 1) + ": " + text);
            chunk.setAction(PdfAction.gotoLocalPage("loc" + (loc.getPage() + 1), false));
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(chunk), 50,
                    height - 100 - (i % MAX_ITEMS_PER_PAGE) * 20, 0);
        }
        document.close();

        return true;
    } catch (Exception e) {
        System.err.println("Failed to overlay locations!");
        e.printStackTrace();
        return false;
    }
}

From source file:nz.ac.waikato.cms.doc.OverlayFilename.java

License:Open Source License

/**
 * Performs the overlay./*from  w ww .jav  a  2  s .c  om*/
 *
 * @param input   the input file/dir
 * @param output   the output file/dir
 * @param vpos   the vertical position
 * @param hpos   the horizontal position
 * @param stripPath   whether to strip the path
 * @param stripExt   whether to strip the extension
 * @param pages   the array of pages (1-based) to add the overlay to, null for all
 * @param evenPages   whether to enforce even pages in the document
 * @return      true if successfully overlay
 */
public boolean overlay(File input, File output, int vpos, int hpos, boolean stripPath, boolean stripExt,
        int[] pages, boolean evenPages) {
    PdfReader reader;
    PdfStamper stamper;
    FileOutputStream fos;
    PdfContentByte canvas;
    int i;
    String text;
    int numPages;
    File tmpFile;
    Document document;
    PdfWriter writer;
    PdfImportedPage page;
    PdfContentByte cb;

    reader = null;
    stamper = null;
    fos = null;
    numPages = -1;
    try {
        reader = new PdfReader(input.getAbsolutePath());
        fos = new FileOutputStream(output.getAbsolutePath());
        stamper = new PdfStamper(reader, fos);
        numPages = reader.getNumberOfPages();
        if (pages == null) {
            pages = new int[reader.getNumberOfPages()];
            for (i = 0; i < pages.length; i++)
                pages[i] = i + 1;
        }

        if (stripPath)
            text = input.getName();
        else
            text = input.getAbsolutePath();
        if (stripExt)
            text = text.replaceFirst("\\.[pP][dD][fF]$", "");

        for (i = 0; i < pages.length; i++) {
            canvas = stamper.getOverContent(pages[i]);
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph(text), hpos, vpos, 0.0f);
        }
    } catch (Exception e) {
        System.err.println("Failed to process " + input + ":");
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (stamper != null)
                stamper.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (reader != null)
                reader.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        } catch (Exception e) {
            // ignored
        }
    }

    // enforce even pages?
    if (evenPages && (numPages > 0) && (numPages % 2 == 1)) {
        reader = null;
        fos = null;
        writer = null;
        tmpFile = new File(output.getAbsolutePath() + "tmp");
        try {
            if (!output.renameTo(tmpFile)) {
                System.err.println("Failed to rename '" + output + "' to '" + tmpFile + "'!");
                return false;
            }
            reader = new PdfReader(tmpFile.getAbsolutePath());
            document = new Document(reader.getPageSize(1));
            fos = new FileOutputStream(output.getAbsoluteFile());
            writer = PdfWriter.getInstance(document, fos);
            document.open();
            document.addCreationDate();
            document.addAuthor(System.getProperty("user.name"));
            cb = writer.getDirectContent();
            for (i = 0; i < reader.getNumberOfPages(); i++) {
                page = writer.getImportedPage(reader, i + 1);
                document.newPage();
                cb.addTemplate(page, 0, 0);
            }
            document.newPage();
            document.add(new Paragraph(" ")); // fake content
            document.close();
        } catch (Exception e) {
            System.err.println("Failed to process " + tmpFile + ":");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                // ignored
            }
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception e) {
                // ignored
            }
            try {
                if (writer != null)
                    writer.close();
            } catch (Exception e) {
                // ignored
            }
            if (tmpFile.exists()) {
                try {
                    tmpFile.delete();
                } catch (Exception e) {
                    // ignored
                }
            }
        }
    }

    return true;
}

From source file:org.cejug.yougi.web.report.EventAttendeeCertificate.java

License:Open Source License

public void setCertificateTemplate(PdfWriter writer, String urlTemplate) throws IOException {
    writer.setPageEvent(this);

    PdfReader reader = new PdfReader(urlTemplate);
    page = writer.getImportedPage(reader, 1);
    canvas = writer.getDirectContent();// ww w.  j a v  a  2 s . c  o m
}

From source file:org.dspace.disseminate.CitationDocument.java

/**
 * Attempts to add a Logo to the document from the given resource. Returns
 * true on success and false on failure.
 *
 * @param doc The document to add the logo to. (Added to the top right
 * corner of the first page./*w w  w  . ja v  a2  s .c om*/
 * @param writer The writer associated with the given Document.
 * @param res The resource/path to the logo file. This file can be any of
 * the following formats:
 *  GIF, PNG, JPEG, PDF
 *
 * @return Succesfully added logo to document.
 */
private boolean addLogoToDocument(Document doc, PdfWriter writer, String res) {
    boolean ret = false;
    try {
        //First we try to get the logo as if it is a Java Resource
        URL logoURL = this.getClass().getResource(res);
        log.debug(res + " -> " + logoURL.toString());
        if (logoURL == null) {
            logoURL = new URL(res);
        }

        if (logoURL != null) {
            String mtype = URLConnection.guessContentTypeFromStream(logoURL.openStream());
            if (mtype == null) {
                mtype = URLConnection.guessContentTypeFromName(res);
            }
            log.debug("Determined MIMETYPE of logo: " + mtype);
            if (PDF_MIMES.contains(mtype)) {
                //Handle pdf logos.
                PdfReader reader = new PdfReader(logoURL);
                PdfImportedPage logoPage = writer.getImportedPage(reader, 1);
                Image logo = Image.getInstance(logoPage);
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                doc.add(logo);
                ret = true;
            } else if (RASTER_MIMES.contains(mtype)) {
                //Use iText's Image class
                Image logo = Image.getInstance(logoURL);

                //Determine the position of the logo (upper-right corner) and
                //place it there.
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                writer.getDirectContent().addImage(logo);
                ret = true;
            } else if (SVG_MIMES.contains(mtype)) {
                //Handle SVG Logos
                log.error("SVG Logos are not supported yet.");
            } else {
                //Cannot use other mimetypes
                log.debug("Logo MIMETYPE is not supported.");
            }
        } else {
            log.debug("Could not create URL to Logo resource: " + res);
        }
    } catch (Exception e) {
        log.error("Could not add logo (" + res + ") to cited document: " + e.getMessage());
        ret = false;
    }
    return ret;
}

From source file:org.gmdev.pdftrick.engine.MergeFiles.java

License:Open Source License

/**
 * Materially multiple pdf files are written merged file on a disk 
 * @param list//from w w w.  j ava2 s.  c  o  m
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
private void doMerge(List<StreamPwdContainer> list, OutputStream outputStream)
        throws DocumentException, IOException {
    HashMap<Integer, String> rotationFromPages = factory.getRotationFromPages();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    int z = 0;
    for (StreamPwdContainer boom : list) {

        InputStream in = boom.getIn();
        PdfReader reader = null;
        if (!boom.getPwd().equalsIgnoreCase("")) {
            reader = new PdfReader(in, boom.getPwd().getBytes());
        } else {
            reader = new PdfReader(in);
        }

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            z++;
            int rotation = reader.getPageRotation(i);

            //set size
            Rectangle pageSize_ = reader.getPageSize(i);
            Rectangle pageSize = null;
            if (rotation == 270 || rotation == 90) {
                pageSize = new Rectangle(pageSize_.getHeight(), pageSize_.getWidth());
            } else {
                pageSize = pageSize_;
            }

            document.setPageSize(pageSize);
            writer.setCropBoxSize(pageSize);

            document.newPage();

            // import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);

            // add the page to the destination pdf
            if (rotation == 270) {
                cb.addTemplate(page, 0, 1.0f, -1.0f, 0, reader.getPageSizeWithRotation(i).getWidth(), 0);
                rotationFromPages.put(z, "" + rotation);
            } else if (rotation == 180) {
                cb.addTemplate(page, -1f, 0, 0, -1f, 0, 0);
                rotationFromPages.put(z, "" + rotation);
            } else if (rotation == 90) {
                cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
                rotationFromPages.put(z, "" + rotation);
            } else {
                cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
        }
        in.close();
    }
    outputStream.flush();
    document.close();
    outputStream.close();
}

From source file:org.zaproxy.zap.extension.alertReport.AlertReportExportPDF.java

License:Apache License

public boolean exportAlert(java.util.List<java.util.List<Alert>> alerts, String fileName,
        ExtensionAlertReportExport extensionExport) {
    Document document = new Document(PageSize.A4);
    try {/*from  ww  w.jav a2  s .  c o  m*/
        // Document documentAdd = null;
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        boolean attach = false;
        // add attach document is exist
        if (!extensionExport.getParams().getDocumentAttach().isEmpty()) {
            PdfReader reader = new PdfReader(extensionExport.getParams().getDocumentAttach());
            int n = reader.getNumberOfPages();
            PdfImportedPage page;
            // Go through all pages
            for (int i = 1; i <= n; i++) {
                page = writer.getImportedPage(reader, i);
                Image instance = Image.getInstance(page);
                instance.scalePercent(95f);
                document.add(instance);
            }
            attach = true;
        }
        if (!attach) {
            addMetaData(document, extensionExport);
            addTitlePage(document, extensionExport);
        }
        for (int i = 0; i < alerts.size(); i++) {
            java.util.List<Alert> alertAux = alerts.get(i);
            addContent(document, alertAux, extensionExport);
        }

        document.close();
        return true;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        document.close();
        return false;
    }

}

From source file:pdf.SplitPDF.java

public static void splitPDF(InputStream inputStream, OutputStream outputStream, int fromPage, int toPage) {
    Document document = new Document();
    try {/*from   www.j a  v  a 2s.  c o  m*/
        PdfReader inputPDF = new PdfReader(inputStream);

        int totalPages = inputPDF.getNumberOfPages();

        //make fromPage equals to toPage if it is greater
        if (fromPage > toPage) {
            fromPage = toPage;
        }
        if (toPage > totalPages) {
            toPage = totalPages;
        }

        // Create a writer for the outputstream
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        PdfImportedPage page;

        while (fromPage <= toPage) {
            document.newPage();
            page = writer.getImportedPage(inputPDF, fromPage);
            cb.addTemplate(page, 0, 0);
            fromPage++;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}