Example usage for com.itextpdf.text Document setPageSize

List of usage examples for com.itextpdf.text Document setPageSize

Introduction

In this page you can find the example usage for com.itextpdf.text Document setPageSize.

Prototype


public boolean setPageSize(Rectangle pageSize) 

Source Link

Document

Sets the pagesize.

Usage

From source file:org.restate.project.controller.PaymentReceiptController.java

License:Open Source License

@RequestMapping(method = RequestMethod.GET, value = "receipt.print")
public void downloadDocument(HttpServletResponse response,
        @RequestParam(value = "id", required = false) Integer id) throws Exception {

    if (id == null) {
        return;//from ww w .  j  ava  2  s.c  o m
    }

    // creation of the document with a certain size and certain margins
    // may want to use PageSize.LETTER instead
    // Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    Document doc = new Document();
    PdfWriter docWriter = null;

    DecimalFormat df = new DecimalFormat("0.00");
    File tmpFile = File.createTempFile("paymentReceipt", ".pdf");

    try {

        //special font sizes
        Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0));
        Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 12);

        //file path

        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(tmpFile));

        //document header attributes
        doc.addAuthor("betterThanZero");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("MySampleCode.com");
        doc.addTitle("Report with Column Headings");
        doc.setPageSize(PageSize.LETTER);

        //open document
        doc.open();

        //create a paragraph
        Paragraph paragraph = new Paragraph("iText  is a library that allows you to create and "
                + "manipulate PDF documents. It enables developers looking to enhance web and other "
                + "applications with dynamic PDF document generation and/or manipulation.");

        //specify column widths
        float[] columnWidths = { 1.5f, 2f, 5f, 2f };
        //create PDF table with the given widths
        PdfPTable table = new PdfPTable(columnWidths);
        // set table width a percentage of the page width
        table.setWidthPercentage(90f);

        //insert column headings
        insertCell(table, "Order No", Element.ALIGN_RIGHT, 1, bfBold12);
        insertCell(table, "Account No", Element.ALIGN_LEFT, 1, bfBold12);
        insertCell(table, "Account Name", Element.ALIGN_LEFT, 1, bfBold12);
        insertCell(table, "Order Total", Element.ALIGN_RIGHT, 1, bfBold12);
        table.setHeaderRows(1);

        //insert an empty row
        insertCell(table, "", Element.ALIGN_LEFT, 4, bfBold12);
        //create section heading by cell merging
        insertCell(table, "New York Orders ...", Element.ALIGN_LEFT, 4, bfBold12);
        double orderTotal, total = 0;

        //just some random data to fill
        for (int x = 1; x < 5; x++) {

            insertCell(table, "10010" + x, Element.ALIGN_RIGHT, 1, bf12);
            insertCell(table, "ABC00" + x, Element.ALIGN_LEFT, 1, bf12);
            insertCell(table, "This is Customer Number ABC00" + x, Element.ALIGN_LEFT, 1, bf12);

            orderTotal = Double.valueOf(df.format(Math.random() * 1000));
            total = total + orderTotal;
            insertCell(table, df.format(orderTotal), Element.ALIGN_RIGHT, 1, bf12);

        }
        //merge the cells to create a footer for that section
        insertCell(table, "New York Total...", Element.ALIGN_RIGHT, 3, bfBold12);
        insertCell(table, df.format(total), Element.ALIGN_RIGHT, 1, bfBold12);

        //repeat the same as above to display another location
        insertCell(table, "", Element.ALIGN_LEFT, 4, bfBold12);
        insertCell(table, "California Orders ...", Element.ALIGN_LEFT, 4, bfBold12);
        orderTotal = 0;

        for (int x = 1; x < 7; x++) {

            insertCell(table, "20020" + x, Element.ALIGN_RIGHT, 1, bf12);
            insertCell(table, "XYZ00" + x, Element.ALIGN_LEFT, 1, bf12);
            insertCell(table, "This is Customer Number XYZ00" + x, Element.ALIGN_LEFT, 1, bf12);

            orderTotal = Double.valueOf(df.format(Math.random() * 1000));
            total = total + orderTotal;
            insertCell(table, df.format(orderTotal), Element.ALIGN_RIGHT, 1, bf12);

        }
        insertCell(table, "California Total...", Element.ALIGN_RIGHT, 3, bfBold12);
        insertCell(table, df.format(total), Element.ALIGN_RIGHT, 1, bfBold12);

        //add the PDF table to the paragraph
        paragraph.add(table);
        // add the paragraph to the document
        doc.add(paragraph);

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (doc != null) {
            //close the document
            doc.close();

        }
        if (docWriter != null) {
            //close the writer
            docWriter.close();
        }

        response.setHeader("Content-disposition", "attachment; filename=" + "sampleDoc" + ".pdf");
        response.setContentType("application/pdf");
        OutputStream outputStream = response.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(tmpFile);

        IOUtils.copy(fileInputStream, outputStream);
        fileInputStream.close();
        outputStream.flush();

        tmpFile.delete();
    }

}

From source file:org.tvd.thptty.management.report.Report.java

public void createFile(int kind) {
    Document document = new Document();
    document.setPageSize(PageSize.A4);
    if (kind == 1) {
        document.setMargins(37, 37, 37, 37);
    } else if (kind == 2) {

    }//from  ww w  . ja va  2  s .  c  om
    try {
        File file = new File(getFullPathFile());
        PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        addMetaData(document);
        //addTitlePage(document);
        addContent(document, kind);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        document.close();
    }
}

From source file:Outras.GerarPdf.java

public GerarPdf(Os os) {
    //Criar um documento vazio
    Document documentoPDF = new Document();

    try {//from   www  .  ja va  2  s  . c  om
        //cria uma instancia do documento e da o nome dele na saida informada
        PdfWriter.getInstance(documentoPDF, new FileOutputStream("C:\\OrdensDeServico\\OS_" + os.getId()));

        //abertura do documento
        documentoPDF.open();

        //especificar o layout da pagina; j cria a primeria pagina
        documentoPDF.setPageSize(PageSize.A4);

        ////adicionando pargrafos na primeira folha
        //adicionando titulo
        documentoPDF.addTitle("Ordem de Servio");

        //adicionando imagens da OS e redimensionando
        Image imagem = Image.getInstance(
                "C:\\Users\\aluno\\Documents\\NetBeansProjects\\e-commerce\\src\\material\\imagemOs.png");
        imagem.scaleToFit(200, 200);
        documentoPDF.add(imagem);

        //adicionando o primeiro paragrafo
        documentoPDF.add(new Paragraph("ORDEM DE SERVIO EMITIDA PELO CARRINHO DO USUARIO: "
                + os.getEntrega().getEndereco().getUsuario().getNome()));

        documentoPDF
                .add(new Paragraph("Endereo de entrega: " + os.getEntrega().getEndereco().getLogradouro()));

        documentoPDF.add(new Paragraph("Entregador: " + os.getEntrega().getFuncionario().getNome()));

        documentoPDF.add(new Paragraph("Produtos: "));
        for (Produto p : os.getCarrinho().getProdutos()) {
            documentoPDF.add(new LineSeparator());
            documentoPDF.add(new Paragraph(p.getNome()));
        }
        documentoPDF.add(new LineSeparator());

    } catch (DocumentException de) {
        JOptionPane.showMessageDialog(null, "Erro ao gerar o pdf" + de.getMessage());
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(null, "Erro ao gerar o pdf" + ioe.getMessage());
    } finally {
        documentoPDF.close();
    }

}

From source file:pdf.CoverLetterUtility.java

License:Apache License

public void createPdf() {
    System.out.println("Creating cover letter...");
    Document document = new Document();
    document.setPageSize(PageSize.A4);
    document.setMargins(62, 48, 36, 36);
    baos = new ByteArrayOutputStream();
    try {/*from   w  w w .  ja  v a  2s.c o  m*/
        PdfWriter.getInstance(document, baos);
    } catch (DocumentException ex) {
        Logger.getLogger(CoverLetterUtility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }

    document.open();
    document.addAuthor("vitaelifetime@gmail.com");
    document.addCreationDate();

    addTitle(document);
    addReference(document);
    addSalutation(document);
    addIntroduction(document);
    addWhyMe(document);
    addWhyYou(document);
    addConclusion(document);
    document.close();
}

From source file:pdf.GeradorPDF.java

public void createPdf(String filename, Pagamento pagamento, DadosEspecificos dados)
        throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    document.setPageSize(PageSize.A4.rotate());
    document.setMargins(0, 0, 50, 50);//from   www .j av  a2  s. co m
    Collections.sort(pagamento.getBeneficios(), new Comparator());
    document.open();
    document.add(createTable(pagamento, dados));
    document.close();
}

From source file:pdf.PdfUtility.java

public void createPdf() {
    Logger.getLogger(PdfUtility.class.getName()).log(Level.INFO, "Creating pdf...");
    Document document = new Document();
    try {// w  ww . j av  a  2  s . c o m
        document.setPageSize(PageSize.A4);
        document.setMargins(62, 48, 36, 36);
        baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        document.open();
        addTitle(document);
        addData(document);
    } catch (DocumentException ex) {
        Logger.getLogger(PdfUtility.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(PdfUtility.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        document.close();
    }
}

From source file:pdfcreator.PDFCreator.java

License:Open Source License

@SuppressWarnings("static-access")
protected void createPdf(String filename, String[] images) throws Exception {
    Document doc = new Document();
    PdfWriter writer;//from ww w  . j  a  v a2 s  . co m

    if (pdfxConformance.equals("PDFA1A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1A);
    } else if (pdfxConformance.equals("PDFA1B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1B);
    } else if (pdfxConformance.equals("PDFA2A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_2A);
    } else if (pdfxConformance.equals("PDFA2B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_2B);
    } else if (pdfxConformance.equals("PDFA3A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_3A);
    } else if (pdfxConformance.equals("PDFA3B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_3B);
    } else {
        writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
    }

    if (pdfVersion.equals("1.4")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_4);
    } else if (pdfVersion.equals("1.5")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_5);
    } else if (pdfVersion.equals("1.6")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_6);
    } else if (pdfVersion.equals("1.7")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_7);
    } else {
        writer.setPdfVersion(PdfWriter.VERSION_1_4);
    }

    verbose(filename + ": open");

    doc.addCreationDate();
    doc.addCreator(creator);

    if (title != null) {
        doc.addTitle(title);
    }

    for (int i = 0; i < images.length; i++) {
        verbose(" +" + images[i]);

        Image img = Image.getInstance(images[i]);

        doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
        doc.setMargins(0, 0, 0, 0);

        if (doc.isOpen()) {
            doc.newPage();
        } else {
            doc.open();
        }

        doc.add(img);

        doc.newPage();
    }

    ICC_Profile icc = getImageColorProfile(images[0]);

    if (icc == null) {
        System.err.println("warning: no color profile available in " + images[0] + " using " + profileName);
        icc = getDefaultColorProfile();
    }

    writer.setOutputIntents("Custom", "", null, null, icc);

    writer.createXmpMetadata();

    doc.close();

    verbose(filename + ": close");
}

From source file:PDFIMG.IMAGEStoPDF.java

public static void convertToIMG(String[] RESOURCES, String result, String path, int s)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {
    System.out.println(":)");

    // step 1/*w  w  w.j  av a2s.co  m*/
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
    // step 3
    document.open();
    // step 4
    // Adding a series of images
    Image img;
    System.out.println(":) :)");
    for (String image : RESOURCES) {
        System.out.println(image);

        img = Image.getInstance(path + image);

        document.setPageSize(img);
        document.newPage();
        img.setAbsolutePosition(0, 0);
        document.add(img);
        System.out.println(":(");
    }
    System.out.println(":) :) :) Pdf is outo");
    // step 5
    document.close();

    if (s == 1) {
        JOptionPane.showMessageDialog(null, "Converted Successfully");
        //JOptionPane.showMessageDialog(null, "Finished\nFile save in :\nC:\\DjVu++Task\\ImagestoPDF\\"+RESOURCES[0].substring(0,RESOURCES[0].lastIndexOf("."))+".pdf");
    }
}

From source file:pl.marcinmilkowski.hocrtopdf.Main.java

License:Open Source License

/**
 * @param args/*from   ww  w  . ja va 2 s. co m*/
 */
public static void main(String[] args) {
    try {
        if (args.length < 1 || args[0] == "--help" || args[0] == "-h") {
            System.out.print("Usage: java pl.marcinmilkowski.hocrtopdf.Main INPUTURL.html OUTPUTURL.pdf\n"
                    + "\n" + "Converts hOCR files into PDF\n" + "\n"
                    + "Example: java pl.marcinmilkowski.hocrtopdf.Main hocr.html output.pdf\n");
            if (args.length < 1)
                System.exit(-1);
            else
                System.exit(0);
        }
        URL inputHOCRFile = null;
        FileOutputStream outputPDFStream = null;
        try {
            File file = new File(args[0]);
            inputHOCRFile = file.toURI().toURL();
        } catch (MalformedURLException e) {
            System.out.println("The first parameter has to be a valid file.");
            System.out.println("We got an error: " + e.getMessage());
            System.exit(-1);
        }
        try {
            outputPDFStream = new FileOutputStream(args[1]);
        } catch (FileNotFoundException e) {
            System.out.println("The second parameter has to be a valid URL");
            System.exit(-1);
        }

        // The resolution of a PDF file (using iText) is 72pt per inch
        float pointsPerInch = 72.0f;

        // Using the jericho library to parse the HTML file
        Source source = new Source(inputHOCRFile);

        int pageCounter = 1;

        Document pdfDocument = null;
        PdfWriter pdfWriter = null;
        PdfContentByte cb = null;
        RandomAccessFileOrArray ra = null;

        // Find the tag of class ocr_page in order to load the scanned image
        StartTag pageTag = source.getNextStartTag(0, "class", OCRPAGE);
        while (pageTag != null) {
            int prevPos = pageTag.getEnd();
            Pattern imagePattern = Pattern.compile("image\\s+([^;]+)");
            Matcher imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
            if (!imageMatcher.find()) {
                System.out.println("Could not find a tag of class \"ocr_page\", aborting.");
                System.exit(-1);
            }
            // Load the image
            Image pageImage = null;
            try {
                File file = new File(imageMatcher.group(1));
                pageImage = Image.getInstance(file.toURI().toURL());
            } catch (MalformedURLException e) {
                System.out.println("Could not load the scanned image from: " + "file://" + imageMatcher.group(1)
                        + ", aborting.");
                System.exit(-1);
            }
            if (pageImage.getOriginalType() == Image.ORIGINAL_TIFF) { // this might
                                                                      // be
                                                                      // multipage
                                                                      // tiff!
                File file = new File(imageMatcher.group(1));
                if (pageCounter == 1 || ra == null) {
                    ra = new RandomAccessFileOrArray(file.toURI().toURL());
                }
                int nPages = TiffImage.getNumberOfPages(ra);
                if (nPages > 0 && pageCounter <= nPages) {
                    pageImage = TiffImage.getTiffImage(ra, pageCounter);
                }
            }
            int dpiX = pageImage.getDpiX();
            if (dpiX == 0) { // for images that don't set the resolution we assume
                             // 300 dpi
                dpiX = 300;
            }
            int dpiY = pageImage.getDpiY();
            if (dpiY == 0) { // as above for dpiX
                dpiY = 300;
            }
            float dotsPerPointX = dpiX / pointsPerInch;
            float dotsPerPointY = dpiY / pointsPerInch;
            float pageImagePixelHeight = pageImage.getHeight();
            if (pdfDocument == null) {
                pdfDocument = new Document(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
                pdfDocument.open();
                // Put the text behind the picture (reverse for debugging)
                // cb = pdfWriter.getDirectContentUnder();
                cb = pdfWriter.getDirectContent();
            } else {
                pdfDocument.setPageSize(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfDocument.newPage();
            }
            // first define a standard font for our text
            BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
            Font defaultFont = new Font(base, 8);
            // FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD,
            // CMYKColor.BLACK);

            cb.setHorizontalScaling(1.0f);

            pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
            pageImage.setAbsolutePosition(0, 0);
            // Put the image in front of the text (reverse for debugging)
            // pdfWriter.getDirectContent().addImage(pageImage);
            pdfWriter.getDirectContentUnder().addImage(pageImage);

            // In order to place text behind the recognised text snippets we are
            // interested in the bbox property
            Pattern bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
            // This pattern separates the coordinates of the bbox property
            Pattern bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
            // Only tags of the ocr_line class are interesting
            StartTag ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            while (ocrTag != null) {
                prevPos = ocrTag.getEnd();
                if ("ocrx_word".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                    net.htmlparser.jericho.Element lineElement = ocrTag.getElement();
                    Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
                    if (bboxMatcher.find()) {
                        // We found a tag of the ocr_line class containing a bbox property
                        Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                        bboxCoordinateMatcher.find();
                        int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                                Integer.parseInt((bboxCoordinateMatcher.group(2))),
                                Integer.parseInt((bboxCoordinateMatcher.group(3))),
                                Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                        String line = lineElement.getContent().getTextExtractor().toString();
                        float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                        float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                        // Put the text into the PDF
                        cb.beginText();
                        // Comment the next line to debug the PDF output (visible Text)
                        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                        // height
                        cb.setFontAndSize(defaultFont.getBaseFont(), Math.max(Math.round(bboxHeightPt), 1));
                        // width
                        cb.setHorizontalScaling(bboxWidthPt / cb.getEffectiveStringWidth(line, false));
                        cb.moveText((coordinates[0] / dotsPerPointX),
                                ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                        cb.showText(line);
                        cb.endText();
                        cb.setHorizontalScaling(1.0f);
                    }
                } else {
                    if ("ocr_page".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                        pageCounter++;
                        pageTag = ocrTag;
                        break;
                    }
                }
                ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            }
            if (ocrTag == null) {
                pdfDocument.close();
                break;
            }
        }
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:printInv.GenerateInvoice.java

private void createPDF(String pdfFilename) {

    Document doc = new Document();
    PdfWriter docWriter = null;/*from w w  w.j a v  a 2s.  co m*/
    initializeFonts();

    try {
        //   String path = "docs/" + pdfFilename;
        String path = pdfFilename;
        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.addAuthor("SmartWMS");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("SmartWMS");
        doc.addTitle("Invoice");
        doc.setPageSize(PageSize.LETTER);

        doc.open();
        PdfContentByte cb = docWriter.getDirectContent();

        boolean beginPage = true;
        int y = 0;
        System.out.println("n ===========" + n);
        for (int i = 0; i < n; i++) {
            if (beginPage) {
                beginPage = false;
                generateLayout(doc, cb);
                generateHeader(doc, cb);
                y = 615;
            }
            generateDetail(doc, cb, i, y);
            y = y - 15;
            if (y < 50) {
                printPageNumber(cb);
                doc.newPage();
                beginPage = true;
            }
        }
        printPageNumber(cb);
        cb.beginText();
        cb.setFontAndSize(bfBold, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "Grand Total : " + total, 570, 35, 0);
        cb.endText();

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (doc != null) {
            doc.close();
        }
        if (docWriter != null) {
            docWriter.close();
        }
    }
}