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:book.pdftemplates.FillTemplateHelper.java

@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    background = writer.getImportedPage(reader, 1);
    total = writer.getDirectContent().createTemplate(30, 15);
    today = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(new Date());
}

From source file:br.jus.jfpr.Divisor1.java

/**
 * Divide um arquivo inicialmente em 2, testa se o tamanho que todos
 * arquivos ficaram dentro do limite, se no ficaram apaga tudo e recomea
 * dividindo por, 3, 4, 5, etc. at que todos arquivo fiquem dentro do
 * limite//w ww .  j a v  a  2s .  c o m
 *
 * @param arquivoEntrada O arquivo que ser dividido
 * @param arquivoSaida O nome do arquivo que ser criado
 * @param tamArqSel Tamanho selecionado que devero ficar os arquivos
 * divididos
 * @return String informativa do resultado
 */
public static String dividePDF(File arquivoEntrada, String arquivoSaida, int tamArqSel) {

    int daPagina = 1;
    int paraPagina;
    int tamInicial;
    // FileOutputStream arquivoSair = null;
    String MensagemErro = "ok";
    int fatorDivisao = 2; //Incialmente dividir em 2
    arquivoSaida = arquivoSaida.substring(0, arquivoSaida.indexOf('.')) + "-divido"; //PAra definir o nome do arquivo de sada

    try {
        PdfReader PdfDeEntrada = new PdfReader(arquivoEntrada.getAbsolutePath()); //Para ler o arquivo de entrada
        final int totalPaginas = PdfDeEntrada.getNumberOfPages(); //Verifica o total de pginas
        tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Define o tamanho (em pginas) do 1 arquivo e em quanto dever incrementar(sero o mesmo)
        PdfImportedPage pagina;

        int i = 1; //Contador simples
        while (i <= fatorDivisao && totalPaginas > fatorDivisao) { //Enquanto no fizer todas as divises
            Document documento = new Document();
            FileOutputStream arquivoSair = new FileOutputStream(arquivoSaida + "-" + i + ".pdf"); //Cria o arquivo, vazio
            PdfWriter writer = PdfWriter.getInstance(documento, arquivoSair); //
            documento.open();
            PdfContentByte PContentByte = writer.getDirectContent();
            while (daPagina <= paraPagina) {
                documento.newPage(); //Aloca uma nova pginA
                pagina = writer.getImportedPage(PdfDeEntrada, daPagina); //Seleciona uma pgina especfica. indicada pelo contador
                PContentByte.addTemplate(pagina, 0, 0); //Adiciona a pagina ao contedo
                daPagina++; //Contador simples
            }
            arquivoSair.flush();
            documento.close(); //Grava o arquivo de sada
            arquivoSair.close();
            File arquivoDest = new File(arquivoSaida + "-" + i + ".pdf");
            if (arquivoDest.length() > tamArqSel) { // O tamanho do arquivo de destino ficou maior do que deveria
                delete(arquivoSaida, i); //Chamar a funo para deletar todos arquivos at a chave i
                daPagina = i = 1; //Para recomear tudo de novo
                fatorDivisao++; //Se um arquivo ficou maior, ento deve aumentar a diviso
                tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Para recomear tudo de novo
            } else {
                i++; //Continua a divisao
                if (i == fatorDivisao) { //Ou seja, chegou a ultima divisao
                    paraPagina = totalPaginas; //O ultimo arquivo conter mais pginas
                } else {
                    paraPagina += tamInicial; //Cada arquivo ter o mesmo nmero de pginas//Incrementa sempre o tamanho inicial
                }
            }
        }
    } catch (IOException | DocumentException e) {
        System.err.println(e.getMessage());
        MensagemErro = e.getMessage();
    }
    return MensagemErro;
}

From source file:co.com.realtech.mariner.util.files.PDFUtils.java

public static File agregarTexto(byte[] bytes, String text) {
    File temp = null;//from   w  ww.  j  a  v  a  2s .c om
    try {
        temp = File.createTempFile("archivo", ".pdf");
        OutputStream oos = new FileOutputStream(temp);
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, oos);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        //InputStream targetStream = new FileInputStream(initialFile);
        // Load existing PDF
        PdfReader reader = new PdfReader(bis);
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        // Copy first page of existing PDF into output PDF
        document.setPageSize(reader.getPageSize(1));
        document.newPage();
        cb.addTemplate(page, 0, 0);

        ColumnText ct = new ColumnText(cb);
        Phrase myText = new Phrase(text);
        Font fuente = new Font();
        fuente.setSize(6);
        myText.setFont(fuente);
        ct.setSimpleColumn(myText, 0, -1, document.right(), document.top(), -10, Element.ALIGN_RIGHT);
        ct.go();

        ColumnText ct2 = new ColumnText(cb);
        Phrase myText2 = new Phrase(text);
        Font fuente2 = new Font();
        fuente2.setSize(6);
        myText2.setFont(fuente);
        ct2.setSimpleColumn(myText, 0, -1, document.right(), document.top(), 248, Element.ALIGN_RIGHT);
        ct2.go();

        ColumnText ct3 = new ColumnText(cb);
        Phrase myText3 = new Phrase(text);
        Font fuente3 = new Font();
        fuente3.setSize(6);
        myText3.setFont(fuente);
        ct3.setSimpleColumn(myText, 0, -1, document.right(), document.top(), 505, Element.ALIGN_RIGHT);
        ct3.go();

        document.close();
    } catch (Exception e) {
        System.out.println("e = " + e);
    }
    return temp;
}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

public String createInvoicePDF(String imagePath, String OUTPUT_FILEPATH)
        throws FileNotFoundException, IOException, DocumentException, InterruptedException, URISyntaxException {

    float currPosition = 0;
    String sFilepath = OUTPUT_FILEPATH;
    Image image = Image.getInstance(imagePath);
    //create a paragraph
    Paragraph paragraph = new Paragraph();
    Document d = new Document(PageSize.A4_LANDSCAPE.rotate());
    PdfWriter w = PdfWriter.getInstance(d, new FileOutputStream(sFilepath));
    d.open();//from  ww w  . j a  va 2 s  .  co  m
    PdfContentByte cb = w.getDirectContent();
    ByteArrayOutputStream stampedBuffer;
    URL resource = this.getClass().getClassLoader().getResource(ShippingConstants.INVOICE_TEMPLATE);
    File file = new File(resource.toURI());
    PdfReader templateReader = new PdfReader(new FileInputStream(file));
    stampedBuffer = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(templateReader, stampedBuffer);
    stamper.setFormFlattening(true);
    AcroFields form = stamper.getAcroFields();
    float[] columnWidths = { 1f, 1f, 1f, 3f };
    //create PDF table with the given widths
    PdfPTable table = new PdfPTable(columnWidths);
    // form.setField("field1", String.format("Form Text %d", i+1));
    form.setField("OBName", "Ragav");
    form.setField("OBCompany", "Ragav");
    form.setField("OBAddress", "2002 SW Sarazen Cr");
    form.setField("OBCity", "Bentonville");
    form.setField("OBPhone", "1234567890");
    form.setField("STName", "Ragav");
    form.setField("STCompany", "Ragav");
    form.setField("STAddress", "2002 SW Sarazen Cr");
    form.setField("STCity", "Bentonville");
    form.setField("STPhone", "1234567890");
    form.setField("itemNo", "12334535");
    form.setField("itemDesc", "Laundry Bag");
    stamper.close();
    templateReader.close();
    form = null;
    stamper.close();
    templateReader.close();
    PdfReader stampedReader = new PdfReader(stampedBuffer.toByteArray());
    PdfImportedPage page = w.getImportedPage(stampedReader, 1);
    cb.addTemplate(page, 0, currPosition);
    image.scaleAbsoluteHeight(325);
    image.scaleAbsoluteWidth(550);
    image.setRotationDegrees(270);
    image.setAbsolutePosition(450, 20);
    d.add(image);
    d.close();
    w.close();

    return sFilepath;
}

From source file:com.ephesoft.dcma.util.PDFUtil.java

License:Open Source License

/**
 * The <code>getSelectedPdfFile</code> method is used to limit the file
 * to the page limit given.//from ww w.j av a  2s  .c o m
 * 
 * @param pdfFile {@link File} pdf file from which limit has to be applied
 * @param pageLimit int
 * @throws IOException if file is not found
 * @throws DocumentException if document cannot be created
 */
public static void getSelectedPdfFile(final File pdfFile, final int pageLimit)
        throws IOException, DocumentException {
    PdfReader reader = null;
    Document document = null;
    PdfContentByte contentByte = null;
    PdfWriter writer = null;
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    File newFile = null;
    if (null != pdfFile && pdfFile.exists()) {
        try {
            document = new Document();
            fileInputStream = new FileInputStream(pdfFile);

            String name = pdfFile.getName();
            final int indexOf = name.lastIndexOf(IUtilCommonConstants.DOT);
            name = name.substring(0, indexOf);
            final String finalPath = pdfFile.getParent() + File.separator + name + System.currentTimeMillis()
                    + IUtilCommonConstants.EXTENSION_PDF;
            newFile = new File(finalPath);
            fileOutputStream = new FileOutputStream(finalPath);
            writer = PdfWriter.getInstance(document, fileOutputStream);
            document.open();
            contentByte = writer.getDirectContent();

            reader = new PdfReader(fileInputStream);
            for (int i = 1; i <= pageLimit; i++) {
                document.newPage();

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

                // add the page to the destination pdf
                contentByte.addTemplate(page, 0, 0);
                page.closePath();
            }
        } finally {
            closePassedStream(reader, document, contentByte, writer, fileInputStream, fileOutputStream);
        }
        if (pdfFile.delete() && null != newFile) {
            newFile.renameTo(pdfFile);
        } else {
            if (null != newFile) {
                newFile.delete();
            }
        }
    }
}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

private void addPdf(final File file, final Document document, final PdfWriter writer) throws Exception {
    PdfReader pdfReader = null;/*from  w ww . ja  va 2  s  . c  o  m*/
    try (InputStream is = new FileInputStream(file)) {
        pdfReader = new PdfReader(is);
        PdfContentByte cb = writer.getDirectContent();
        for (int currentPage = 1; currentPage <= pdfReader.getNumberOfPages(); currentPage++) {
            Rectangle currentPageSize = pdfReader.getPageSize(currentPage);
            document.setPageSize(currentPageSize);
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(pdfReader, currentPage);
            cb.addTemplate(page, 0, 0);
            writePageNumber(cb);

        }
        writer.flush();
    } finally {
        if (pdfReader != null) {
            writer.freeReader(pdfReader);
            ItextUtils.close(pdfReader);
        }
    }
}

From source file:com.github.ukase.bulk.BulkRenderTask.java

License:Open Source License

private void appendPdf(Document document, PdfWriter writer, PdfContentByte cb, byte[] pdf) throws IOException {
    PdfReader reader = new PdfReader(pdf);
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        PdfImportedPage page = writer.getImportedPage(reader, i);
        document.newPage();//from  w w w  .j  a v a 2  s.  c  o m
        cb.addTemplate(page, 0, 0);
    }
}

From source file:com.imipgroup.hieuvt.pdf.PdfUtils.java

public Document readPdf(String inputPath) {
    String outputPath = "files/Pdf/testRead.pdf";
    Document document = new Document();
    PdfWriter writer = null;
    try {/*  ww w  .ja v a2 s  . c  om*/
        writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
        document.open();
        PdfReader reader = new PdfReader(inputPath);
        int n = reader.getNumberOfPages();
        PdfImportedPage page;
        // Go through all pages
        for (int i = 1; i <= n; i++) {
            // only page number 2 will be included
            if (i == 2) {
                page = writer.getImportedPage(reader, i);
                Image instance = Image.getInstance(page);
                document.add(instance);
            }
        }
        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return document;
}

From source file:com.kohmiho.mpsr.export.PDFGenerator.java

protected void importPages(Document document, PdfWriter writer, String mpsrID, String fileName)
        throws DocumentException {
    if (null != fileName) {
        String filePath = MPSRUI.getFilePath(mpsrID, fileName);

        PdfReader reader = null;//from  w  w  w. j a va2s . c om
        try {
            reader = new PdfReader(filePath);
        } catch (IOException e) {
            document.add(new Paragraph(String.format("*** Can not load file %s ***", filePath)));
            // e.printStackTrace();
        }

        if (null != reader) {
            for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); pageNum++) {

                document.setPageSize(reader.getPageSize(pageNum));
                document.newPage();

                PdfImportedPage page = writer.getImportedPage(reader, pageNum);

                // addPageByImage(writer, page);
                addPageByTemplate(writer, page);

                document.setPageSize(DEFAULT_PAGE_SIZE);
                document.newPage();
            }
        }
    }
}

From source file:com.photon.phresco.framework.docs.impl.DocumentUtil.java

License:Apache License

/**
 * @param titleSection/*from   w  ww. ja  va 2s.  c  om*/
 * @param writer
 * @param docu
 * @throws PhrescoException 
 */
public static void addPages(InputStream titleSection, PdfWriter writer, com.itextpdf.text.Document docu)
        throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug(
                "Entering Method DocumentUtil.addPages(InputStream titleSection, PdfWriter writer, com.itextpdf.text.Document docu)");
    }
    try {
        PdfReader reader = new PdfReader(titleSection);
        reader.consolidateNamedDestinations();
        PdfContentByte cb = writer.getDirectContent();

        int pages = reader.getNumberOfPages();
        for (int i = 1; i <= pages; i++) {
            PdfImportedPage importedPage = writer.getImportedPage(reader, i);
            cb.addTemplate(importedPage, 0, 0);
            docu.newPage();
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new PhrescoException(e);
    }
}