Example usage for com.lowagie.text.pdf PdfReader getPageSizeWithRotation

List of usage examples for com.lowagie.text.pdf PdfReader getPageSizeWithRotation

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfReader getPageSizeWithRotation.

Prototype

public Rectangle getPageSizeWithRotation(PdfDictionary page) 

Source Link

Document

Gets the rotated page from a page dictionary.

Usage

From source file:QMSMultiQuoteController.java

License:Open Source License

private byte[] concatPDF(ArrayList pdfFilesList) {
    byte[] buffer = null;
    FileOutputStream filestream = null;
    try {//from  w w w .j a v  a2 s.  c  om
        int i = 1;

        Document document = null;
        PdfCopy pdfcopy = null;

        if (pdfFilesList.size() > 1) {
            String s = (String) pdfFilesList.get(0);
            int pdfFilListSize = pdfFilesList.size();
            for (; i < pdfFilListSize; i++) {
                PdfReader pdfreader = new PdfReader((String) pdfFilesList.get(i));
                int j = pdfreader.getNumberOfPages();
                if (i == 1) {
                    document = new Document(pdfreader.getPageSizeWithRotation(1));
                    filestream = new FileOutputStream(s);
                    pdfcopy = new PdfCopy(document, filestream);
                    document.open();
                }
                PdfImportedPage pdfimportedpage = null;
                for (int k = 0; k < j;) {
                    k++;
                    pdfimportedpage = pdfcopy.getImportedPage(pdfreader, k);
                    if (pdfimportedpage != null) {
                        pdfcopy.addPage(pdfimportedpage);
                    }
                }

                com.lowagie.text.pdf.PRAcroForm pracroform = pdfreader.getAcroForm();
                if (pracroform != null)
                    pdfcopy.copyAcroForm(pdfreader);
            }

            if (document != null) {
                document.close();
            }

            FileInputStream inputStream = new FileInputStream(s);
            buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
        }
        // buffer  = pdfcopy.getDirectContent();

    } catch (Exception exception) {
        exception.printStackTrace();
    }
    return buffer;
}

From source file:br.com.nordestefomento.jrimum.utilix.PDFUtil.java

License:Apache License

/**
 * <p>//from  www.  j  a va  2  s. c om
 * Junta varios arquivos pdf em um soh.
 * </p>
 * 
 * @param pdfFiles
 *            Lista de array de bytes
 * 
 * @return Arquivo PDF em forma de byte
 * @since 0.2
 */
@SuppressWarnings("unchecked")
public static byte[] mergeFiles(List<byte[]> pdfFiles) {

    // retorno
    byte[] bytes = null;

    if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) {

        int pageOffset = 0;
        boolean first = true;

        ArrayList master = null;
        Document document = null;
        PdfCopy writer = null;
        ByteArrayOutputStream byteOS = null;

        try {

            byteOS = new ByteArrayOutputStream();
            master = new ArrayList();

            for (byte[] doc : pdfFiles) {

                if (isNotNull(doc)) {

                    // cria-se um reader para cada documento

                    PdfReader reader = new PdfReader(doc);

                    if (reader.isEncrypted()) {
                        reader = new PdfReader(doc, "".getBytes());
                    }

                    reader.consolidateNamedDestinations();

                    // pega-se o numero total de paginas
                    int n = reader.getNumberOfPages();
                    List bookmarks = SimpleBookmark.getBookmark(reader);

                    if (isNotNull(bookmarks)) {
                        if (pageOffset != 0) {
                            SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                        }
                        master.addAll(bookmarks);
                    }

                    pageOffset += n;

                    if (first) {

                        // passo 1: criar um document-object
                        document = new Document(reader.getPageSizeWithRotation(1));

                        // passo 2: criar um writer que observa o documento
                        writer = new PdfCopy(document, byteOS);
                        document.addAuthor("JRimum Group");
                        document.addSubject("JRimum Merged Document");
                        document.addCreator("JRimum Utilix");

                        // passo 3: abre-se o documento
                        document.open();
                        first = false;
                    }

                    // passo 4: adciona-se o conteudo
                    PdfImportedPage page;
                    for (int i = 0; i < n;) {
                        ++i;
                        page = writer.getImportedPage(reader, i);

                        writer.addPage(page);
                    }
                }
            }

            if (master.size() > 0) {
                writer.setOutlines(master);
            }

            // passo 5: fecha-se o documento
            if (isNotNull(document)) {
                document.close();
            }

            bytes = byteOS.toByteArray();

        } catch (Exception e) {
            LOG.error("", e);
        }
    }

    return bytes;
}

From source file:br.gov.jfrj.itextpdf.Documento.java

License:Open Source License

public static byte[] getDocumento(ExMobil mob, ExMovimentacao mov, boolean completo, boolean estampar,
        String hash, byte[] certificado) throws Exception {
    final ByteArrayOutputStream bo2 = new ByteArrayOutputStream();
    PdfReader reader;
    int n;/*from   w  ww.j  ava2  s . c o  m*/
    int pageOffset = 0;
    ArrayList master = new ArrayList();
    int f = 0;
    Document document = null;
    PdfCopy writer = null;
    int nivelInicial = 0;

    // if (request.getRequestURI().indexOf("/completo/") == -1) {
    // return getPdf(docvia, mov != null ? mov : docvia.getExDocumento(),
    // mov != null ? mov.getNumVia() : docvia.getNumVia(), null,
    // null, request);
    // }

    List<ExArquivoNumerado> ans = mob.filtrarArquivosNumerados(mov, completo);

    if (!completo && !estampar && ans.size() == 1) {
        if (certificado != null) {
            CdService cdService = Service.getCdService();
            return cdService.produzPacoteAssinavel(certificado, null, ans.get(0).getArquivo().getPdf(), true,
                    ExDao.getInstance().getServerDateTime());
        } else if (hash != null) {
            // Calcula o hash do documento
            String alg = hash;
            MessageDigest md = MessageDigest.getInstance(alg);
            md.update(ans.get(0).getArquivo().getPdf());
            return md.digest();
        } else {
            return ans.get(0).getArquivo().getPdf();
        }
    }

    try {
        for (ExArquivoNumerado an : ans) {

            // byte[] ab = getPdf(docvia, an.getArquivo(), an.getNumVia(),
            // an
            // .getPaginaInicial(), an.getPaginaFinal(), request);

            String sigla = mob.getSigla();
            if (an.getArquivo() instanceof ExMovimentacao) {
                ExMovimentacao m = (ExMovimentacao) an.getArquivo();
                if (m.getExTipoMovimentacao().getId() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_JUNTADA)
                    sigla = m.getExMobil().getSigla();
            } else {
                sigla = an.getMobil().getSigla();
            }

            byte[] ab = !estampar ? an.getArquivo().getPdf()
                    : stamp(an.getArquivo().getPdf(), sigla, an.getArquivo().isRascunho(),
                            an.getArquivo().isCancelado(), an.getArquivo().isSemEfeito(),
                            an.getArquivo().isInternoProduzido(), an.getArquivo().getQRCode(),
                            an.getArquivo().getMensagem(), an.getPaginaInicial(), an.getPaginaFinal(),
                            an.getOmitirNumeracao(), SigaExProperties.getTextoSuperiorCarimbo(),
                            mob.getExDocumento().getOrgaoUsuario().getDescricao());

            // we create a reader for a certain document

            reader = new PdfReader(ab);
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            n = reader.getNumberOfPages();
            // List bookmarks = SimpleBookmark.getBookmark(reader);
            // master.add(new Bookmark)
            // if (bookmarks != null) {
            // if (pageOffset != 0)
            // SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset,
            // null);
            // master.addAll(bookmarks);
            // }

            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the
                // document
                writer = new PdfCopy(document, bo2);
                writer.setFullCompression();

                // writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);

                // step 3: we open the document
                document.open();

                nivelInicial = an.getNivel();
            }

            // PdfOutline root = writer.getDirectContent().getRootOutline();
            // PdfContentByte cb = writer.getDirectContent();
            // PdfDestination destination = new
            // PdfDestination(PdfDestination.FITH, position);
            // step 4: we add content
            PdfImportedPage page;
            for (int j = 0; j < n;) {
                ++j;
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
                if (j == 1) {
                    // PdfContentByte cb = writer.getDirectContent();
                    // PdfOutline root = cb.getRootOutline();
                    // PdfOutline oline1 = new PdfOutline(root,
                    // PdfAction.gotoLocalPage("1", false),"Chapter 1");

                    HashMap map = new HashMap();
                    map.put("Title", an.getNome());
                    map.put("Action", "GoTo");
                    map.put("Page", j + pageOffset + "");
                    map.put("Kids", new ArrayList());

                    ArrayList mapPai = master;
                    for (int i = 0; i < an.getNivel() - nivelInicial; i++) {
                        mapPai = ((ArrayList) ((HashMap) mapPai.get(mapPai.size() - 1)).get("Kids"));
                    }
                    mapPai.add(map);
                }

            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null)
                writer.copyAcroForm(reader);

            pageOffset += n;
            f++;
        }
        if (!master.isEmpty())
            writer.setOutlines(master);

        // PdfDictionary info = writer.getInfo();
        // info.put(PdfName.MODDATE, null);
        // info.put(PdfName.CREATIONDATE, null);
        // info.put(PdfName.ID, null);

        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bo2.toByteArray();
}

From source file:clases.unirPdf.java

public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {//from   w  w w.  ja  va  2 s  . com
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }

        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        PdfContentByte cb = writer.getDirectContent();

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

        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {

                Rectangle rectangle = pdfReader.getPageSizeWithRotation(1);
                document.setPageSize(rectangle);
                document.newPage();

                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                switch (rectangle.getRotation()) {
                case 0:
                    cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    break;
                case 90:
                    cb.addTemplate(page, 0, -1f, 1f, 0, 0, pdfReader.getPageSizeWithRotation(1).getHeight());
                    break;
                case 180:
                    cb.addTemplate(page, -1f, 0, 0, -1f, 0, 0);
                    break;
                case 270:
                    cb.addTemplate(page, 0, 1.0F, -1.0F, 0, pdfReader.getPageSizeWithRotation(1).getWidth(), 0);
                    break;
                default:
                    break;
                }
                if (paginate) {
                    cb.beginText();
                    cb.getPdfDocument().getPageSize();
                    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:classroom.newspaper_a.Newspaper02.java

public static void main(String[] args) {
    try {//from w  ww. j  av a2  s  . co m
        PdfReader reader = new PdfReader(NEWSPAPER);
        Document document = new Document(reader.getPageSizeWithRotation(1));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        PdfContentByte content = writer.getDirectContent();
        content.rectangle(document.left(), document.bottom(), document.right(), document.top());
        content.rectangle(LLX1, LLY1, W1, H1);
        content.rectangle(LLX2, LLY2, W2, H2);
        content.eoClip();
        content.newPath();
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        content.addTemplate(page, 0, 0);
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:com.benfante.minimark.blo.AssessmentPdfBuilder.java

License:Apache License

/**
 * Build the contatenated PDF for a list of assessments.
 *
 * @param assessments The assessments//from   w  ww.  j a  v  a 2 s  .  c  o m
 * @param baseUrl The base URL for retrieving images and resource. If null it will not be set.
 * @param locale The locale for producing the document. Id null, the default locale will be used.
 * @return The PDF document.
 */
public byte[] buildPdf(List<AssessmentFilling> assessments, String baseUrl, Locale locale) throws Exception {
    ByteArrayOutputStream pdfos = new ByteArrayOutputStream();
    List master = new ArrayList();
    Document document = null;
    PdfCopy writer = null;
    PdfOutline rootOutline = null;
    try {
        int f = 0;
        int pageOffset = 0;
        for (AssessmentFilling assessment : assessments) {
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(buildPdf(assessment, baseUrl, locale));
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;
            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, pdfos);
                writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
                // step 3: we open the document
                document.open();
                // initialize rootOutline for assessment bookmarks creation
                PdfContentByte cb = writer.getDirectContent();
                rootOutline = cb.getRootOutline();
            }
            // step 4: we add content
            new PdfOutline(rootOutline, new PdfDestination(PdfDestination.FIT),
                    assessment.getLastName() + " " + assessment.getFirstName());
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null) {
                writer.copyAcroForm(reader);
            }
            f++;
        }
    } finally {
        if (pdfos != null) {
            try {
                pdfos.close();
            } catch (IOException ioe) {
            }
        }
        if (!master.isEmpty()) {
            writer.setOutlines(master);
        }
        // step 5: we close the document
        if (document != null && document.isOpen()) {
            document.close();
        }
    }
    return pdfos.toByteArray();
}

From source file:com.ikon.util.PDFUtils.java

License:Open Source License

public static void stampImage(InputStream input, byte[] image, int layer, float opacity, String exprX,
        String exprY, OutputStream output)
        throws FileNotFoundException, DocumentException, EvalError, IOException {
    log.debug("stampImage({}, {}, {}, {}, {}, {}, {})", new Object[] { input, image, Integer.valueOf(layer),
            Float.valueOf(opacity), exprX, exprY, output });
    Image img = Image.getInstance(image);
    PdfReader reader = new PdfReader(input);
    PdfStamper stamper = new PdfStamper(reader, output);
    PdfGState gs = new PdfGState();
    gs.setFillOpacity(opacity);/* w w  w  .j  av  a  2s . c  o  m*/
    gs.setStrokeOpacity(opacity);
    int numPages = reader.getNumberOfPages();
    int count = 0;

    while (count++ < numPages) {
        int pageCenter = (int) reader.getPageSizeWithRotation(count).getWidth() / 2;
        int pageMiddle = (int) reader.getPageSizeWithRotation(count).getHeight() / 2;

        Interpreter i = new Interpreter();
        i.set("IMAGE_WIDTH", (int) img.getWidth());
        i.set("IMAGE_HEIGHT", (int) img.getHeight());
        i.set("PAGE_WIDTH", (int) reader.getPageSizeWithRotation(count).getWidth());
        i.set("PAGE_HEIGHT", (int) reader.getPageSizeWithRotation(count).getHeight());
        i.set("PAGE_CENTER", pageCenter);
        i.set("PAGE_MIDDLE", pageMiddle);
        Integer evalX = (Integer) i.eval(exprX);
        Integer evalY = (Integer) i.eval(exprY);

        if (evalX == null)
            evalX = Integer.valueOf(pageCenter);
        if (evalY == null) {
            evalY = Integer.valueOf(pageMiddle);
        }
        log.debug("evalX: {}", evalX);
        log.debug("evalY: {}", evalY);

        img.setAbsolutePosition(evalX.intValue(), evalY.intValue());
        PdfContentByte cb = null;

        if (layer == LAYER_UNDER_CONTENT)
            cb = stamper.getUnderContent(count);
        else if (layer == LAYER_OVER_CONTENT)
            cb = stamper.getOverContent(count);
        else {
            throw new IllegalArgumentException();
        }

        cb.saveState();
        cb.setGState(gs);
        cb.addImage(img);
        cb.restoreState();
    }

    stamper.close();
}

From source file:com.ikon.util.PDFUtils.java

License:Open Source License

public static void stampText(InputStream input, String text, int layer, float opacity, int size, Color color,
        int rotation, int align, String exprX, String exprY, OutputStream output)
        throws FileNotFoundException, DocumentException, EvalError, IOException {
    log.debug("stampText({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})",
            new Object[] { input, text, Integer.valueOf(layer), Float.valueOf(opacity), Integer.valueOf(size),
                    color, Integer.valueOf(rotation), Integer.valueOf(align), exprX, exprY, output });

    BaseFont bf = getBaseFont();//from w w  w  .j a  v a2 s  . c o  m
    PdfReader reader = new PdfReader(input);
    PdfStamper stamper = new PdfStamper(reader, output);
    PdfGState gs = new PdfGState();
    gs.setFillOpacity(opacity);
    gs.setStrokeOpacity(opacity);
    int numPages = reader.getNumberOfPages();
    int count = 0;

    while (count++ < numPages) {
        int pageCenter = (int) reader.getPageSizeWithRotation(count).getWidth() / 2;
        int pageMiddle = (int) reader.getPageSizeWithRotation(count).getHeight() / 2;

        Interpreter i = new Interpreter();
        i.set("PAGE_WIDTH", (int) reader.getPageSizeWithRotation(count).getWidth());
        i.set("PAGE_HEIGHT", (int) reader.getPageSizeWithRotation(count).getHeight());
        i.set("PAGE_CENTER", pageCenter);
        i.set("PAGE_MIDDLE", pageMiddle);
        Integer evalX = (Integer) i.eval(exprX);
        Integer evalY = (Integer) i.eval(exprY);

        if (evalX == null)
            evalX = Integer.valueOf(pageCenter);
        if (evalY == null) {
            evalY = Integer.valueOf(pageMiddle);
        }
        log.debug("evalX: {}", evalX);
        log.debug("evalY: {}", evalY);

        PdfContentByte cb = null;

        if (layer == LAYER_UNDER_CONTENT)
            cb = stamper.getUnderContent(count);
        else if (layer == LAYER_OVER_CONTENT)
            cb = stamper.getOverContent(count);
        else {
            throw new IllegalArgumentException();
        }

        cb.saveState();
        cb.setColorFill(color);
        cb.setGState(gs);
        cb.beginText();
        cb.setFontAndSize(bf, size);
        cb.showTextAligned(align, text, evalX.intValue(), evalY.intValue(), rotation);
        cb.endText();
        cb.restoreState();
    }

    stamper.close();
    reader.close();
}

From source file:com.moss.pdf.template.core.Renderer.java

License:Open Source License

public void render(InputStream in, List<? extends PropertyMapping> fields, OutputStream out) throws Exception {

    PdfReader reader = new PdfReader(in);

    Document document = new Document(reader.getPageSizeWithRotation(1));

    PdfWriter writer = PdfWriter.getInstance(document, out);

    document.open();/*ww  w  .  j  a  v  a 2 s .c  o  m*/

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

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage customPage = writer.getImportedPage(reader, i);

        /*
         * add the page to our new document, turning this page to its 
         * original rotation
         */
        int pageRotation = reader.getPageRotation(i);

        if (pageRotation > 0) {

            System.out.println("page rotation found: " + pageRotation);

            double angle = -((2 * Math.PI) * pageRotation / 360);
            //         double angle = -(Math.PI / 2);

            cb.addTemplate(customPage, (float) Math.cos(angle), (float) Math.sin(angle),
                    (float) -Math.sin(angle), (float) Math.cos(angle), 0f, // x
                    document.top() + document.topMargin() // y
            );
        } else {
            cb.addTemplate(customPage, 0f, 0f);
        }

        Map<FontName, BaseFont> fonts = new HashMap<FontName, BaseFont>();

        for (PropertyMapping field : fields) {

            if (field.getPageNumber() != i) {
                continue;
            }

            /*
             * Only builtin fonts are supported at the moment
             */
            BaseFont font;
            int fontSize;
            int alignment;
            String text;
            float x, y;
            float rotation;

            {
                font = fonts.get(field.getFontName());

                if (font == null) {

                    FontName e = field.getFontName();
                    String name = null;

                    if (FontName.COURIER == e) {
                        name = BaseFont.COURIER;
                    } else if (FontName.COURIER_BOLD == e) {
                        name = BaseFont.COURIER_BOLD;
                    } else if (FontName.COURIER_BOLD_OBLIQUE == e) {
                        name = BaseFont.COURIER_BOLDOBLIQUE;
                    } else if (FontName.COURIER_OBLIQUE == e) {
                        name = BaseFont.COURIER_OBLIQUE;
                    } else if (FontName.HELVETICA == e) {
                        name = BaseFont.HELVETICA;
                    } else if (FontName.HELVETICA_BOLD == e) {
                        name = BaseFont.HELVETICA_BOLD;
                    } else if (FontName.HELVETICA_BOLD_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_BOLDOBLIQUE;
                    } else if (FontName.HELVETICA_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_OBLIQUE;
                    } else if (FontName.TIMES_BOLD == e) {
                        name = BaseFont.TIMES_BOLD;
                    } else if (FontName.TIMES_BOLD_ITALIC == e) {
                        name = BaseFont.TIMES_BOLDITALIC;
                    } else if (FontName.TIMES_ITALIC == e) {
                        name = BaseFont.TIMES_ITALIC;
                    } else if (FontName.TIMES_ROMAN == e) {
                        name = BaseFont.TIMES_ROMAN;
                    }

                    if (name == null) {
                        throw new RuntimeException("Unknown font type: " + e);
                    }

                    font = BaseFont.createFont(name, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
                    fonts.put(field.getFontName(), font);
                }

                fontSize = field.getFontSize();

                if (TextAlignment.LEFT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_LEFT;
                } else if (TextAlignment.CENTER == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_CENTER;
                } else if (TextAlignment.RIGHT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_RIGHT;
                } else {
                    alignment = PdfContentByte.ALIGN_LEFT;
                }

                Object value = p.eval(field.getExpr());

                if (value == null) {
                    text = "";
                } else {
                    text = value.toString();
                }

                x = field.getX() * POINTS_IN_A_CM;
                y = field.getY() * POINTS_IN_A_CM;

                rotation = 0;
            }

            cb.beginText();

            cb.setFontAndSize(font, fontSize);

            cb.showTextAligned(alignment, text, x, y, rotation);

            cb.endText();
        }

        document.newPage();
    }

    reader.close();
    document.close();
}

From source file:com.sapienter.jbilling.server.invoice.PaperInvoiceBatchBL.java

License:Open Source License

/**
 * Takes a list of invoices and replaces the individual PDF files for one
 * single PDF in the destination directory.
 * @param destination//from   w  w  w .  ja  v a2 s .c  o  m
 * @param prefix
 * @param entityId
 * @param invoices
 * @throws PdfFormatException
 * @throws IOException
 */
public void compileInvoiceFiles(String destination, String prefix, Integer entityId, Integer[] invoices)
        throws DocumentException, IOException {

    String filePrefix = Util.getSysProp("base_dir") + "invoices/" + entityId + "-";
    String outFile = destination + prefix + "-batch.pdf";

    int pageOffset = 0;
    ArrayList master = new ArrayList();
    Document document = null;
    PdfCopy writer = null;
    for (int f = 0; f < invoices.length; f++) {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(filePrefix + invoices[f] + "-invoice.pdf");
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int numberOfPages = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0)
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            master.addAll(bookmarks);
        }
        pageOffset += numberOfPages;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, new FileOutputStream(outFile));
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < numberOfPages;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        PRAcroForm form = reader.getAcroForm();
        if (form != null)
            writer.copyAcroForm(reader);

        //release and delete 
        writer.freeReader(reader);
        reader.close();
        File file = new File(filePrefix + invoices[f] + "-invoice.pdf");
        file.delete();
    }
    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    if (document != null) {
        document.close();
    } else {
        LOG.warn("document == null");
    }

    LOG.debug("PDF batch file is ready " + outFile);
}