Example usage for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream

List of usage examples for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPageContentStream PDPageContentStream.

Prototype

public PDPageContentStream(PDDocument doc, PDAppearanceStream appearance) throws IOException 

Source Link

Document

Create a new appearance stream.

Usage

From source file:com.cdd.bao.template.RenderSchema.java

License:Open Source License

public void createPageTemplate() throws IOException {
    RenderContext ctx = new RenderContext();

    renderPageTemplate(ctx);/*from  w w w. j a  va 2s . co  m*/
    if (ctx.width == 0 || ctx.height == 0)
        return;

    PDPage page = new PDPage(new PDRectangle(ctx.width, ctx.height));
    document.addPage(page);

    ctx.stream = new PDPageContentStream(document, page);
    renderPageTemplate(ctx);
    ctx.stream.close();
}

From source file:com.cdd.bao.template.RenderSchema.java

License:Open Source License

public void createPageAssay(Schema.Assay assay) throws IOException {
    RenderContext ctx = new RenderContext();

    renderPageTemplate(ctx);/*from ww  w.j  av  a2 s .c o m*/
    if (ctx.width == 0 || ctx.height == 0)
        return;

    PDPage page = new PDPage(new PDRectangle(ctx.width, ctx.height));
    document.addPage(page);

    ctx.stream = new PDPageContentStream(document, page);
    renderPageAssay(ctx, assay);
    ctx.stream.close();
}

From source file:com.cdd.bao.template.RenderSchema.java

License:Open Source License

public void createPageProperties() throws IOException {
    RenderContext ctx = new RenderContext();

    renderPageHierarchy(ctx, vocab.getPropertyHierarchy());
    if (ctx.width == 0 || ctx.height == 0)
        return;/*from w w w . j a v  a 2  s .  c o  m*/

    PDPage page = new PDPage(new PDRectangle(ctx.width, ctx.height));
    document.addPage(page);

    ctx.stream = new PDPageContentStream(document, page);
    renderPageHierarchy(ctx, vocab.getPropertyHierarchy());
    ctx.stream.close();
}

From source file:com.cdd.bao.template.RenderSchema.java

License:Open Source License

public void createPageValues() throws IOException {
    RenderContext ctx = new RenderContext();

    renderPageHierarchy(ctx, vocab.getValueHierarchy());
    if (ctx.width == 0 || ctx.height == 0)
        return;/*from   ww  w .j a v  a 2 s.co  m*/

    PDPage page = new PDPage(new PDRectangle(ctx.width, ctx.height));
    document.addPage(page);

    ctx.stream = new PDPageContentStream(document, page);
    renderPageHierarchy(ctx, vocab.getValueHierarchy());
    ctx.stream.close();
}

From source file:com.devnexus.ting.web.controller.PdfUtils.java

License:Apache License

public PdfUtils(float margin, String title) throws IOException {
    this.margin = margin;
    doc = new PDDocument();
    baseFont = PDType0Font.load(doc, PdfUtils.class.getResourceAsStream("/fonts/Arial.ttf"));
    headerFont = PDType1Font.HELVETICA_BOLD;
    subHeaderFont = PDType1Font.HELVETICA_BOLD;
    devnexusLogo = PDDocument.load(PdfUtils.class.getResourceAsStream("/fonts/devnexus-logo.pdf"));

    this.currentPage = new PDPage();
    this.pages.add(currentPage);
    this.doc.addPage(currentPage);

    final PDRectangle mediabox = currentPage.getMediaBox();
    this.width = mediabox.getWidth() - 2 * margin;

    float startX = mediabox.getLowerLeftX() + margin;
    float startY = mediabox.getUpperRightY() - margin;

    this.initialHeightCounter = startY;
    this.heightCounter = startY;

    LOGGER.info(String.format(/*www . j  a  v  a 2  s.c o  m*/
            "Margin: %s, width: %s, startX: %s, "
                    + "startY: %s, heightCounter: %s, baseFontSize: %s, headerFontSize: %s",
            margin, width, startX, startY, heightCounter, baseFont, headerFont));

    contents = new PDPageContentStream(doc, currentPage);

    // Add Logo

    final LayerUtility layerUtility = new LayerUtility(doc);
    final PDFormXObject logo = layerUtility.importPageAsForm(devnexusLogo, 0);
    final AffineTransform affineTransform = AffineTransform.getTranslateInstance(100, startY - 50);
    affineTransform.scale(2d, 2d);
    layerUtility.appendFormAsLayer(currentPage, logo, affineTransform, "devnexus-logo");
    this.heightCounter -= 100;

    this.contents.beginText();

    this.contents.setFont(headerFont, headerFontSize);
    this.currentLeading = this.lineSpacing * baseFontSize;
    this.contents.setLeading(this.currentLeading);

    contents.newLineAtOffset(50, heightCounter);

    println(title);

    this.contents.setFont(baseFont, baseFontSize);
    this.currentLeading = this.lineSpacing * baseFontSize;
    this.contents.setLeading(this.currentLeading);

    println();

}

From source file:com.devnexus.ting.web.controller.PdfUtils.java

License:Apache License

void createNewPageIfNecessary() throws IOException {
    if (heightCounter <= 50) {
        LOGGER.info("Adding New Page.");

        this.heightCounter = this.initialHeightCounter;
        this.contents.endText();

        for (Entry<Float, String> rectangle : this.rectangles.entrySet()) {
            this.contents.setNonStrokingColor(Color.decode(rectangle.getValue()));
            this.contents.addRect(0, rectangle.getKey() - 3, 35, 15);
            this.contents.fill();
            LOGGER.info("Reactangle: " + rectangle.getKey() + "|" + rectangle.getValue());
        }/*from   w  w  w .j  a v a  2 s .co m*/

        this.rectangles.clear();

        this.contents.close();
        this.currentPage = new PDPage();
        this.pages.add(currentPage);
        this.doc.addPage(currentPage);
        contents = new PDPageContentStream(doc, this.currentPage);
        this.contents.beginText();
        this.contents.setFont(baseFont, baseFontSize);
        this.currentLeading = this.lineSpacing * baseFontSize;
        this.contents.setLeading(this.currentLeading);
        contents.newLineAtOffset(50, heightCounter);
        distanceFromZero = 0;

    }
}

From source file:com.evanbelcher.DrillBook.DotSheetMaker.java

License:Open Source License

/**
 * Prints all dot sheets to pdf files/*from  w  w  w. j  a va  2  s  .c o  m*/
 */
private void printAllToPdf() throws IOException {
    printing = true;
    String folder = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0,
            Main.getState().getCurrentFileName().length() - 6)) + " Dot Sheets/";
    File f = new File(Main.getFilePath() + folder);
    f.mkdirs();
    PDDocument doc = null;

    String[] chars = new String[26];
    for (int i = 0; i < 26; i++)
        chars[i] = String.valueOf((char) (65 + i));

    try {
        for (String letter : chars) {
            doc = new PDDocument();

            String fileName = Main.getState().getCurrentFileName().substring(0,
                    Main.getState().getCurrentFileName().length() - 6) + " "
                    + DBMenuBar.cleanseFileName(letter);
            f = new File(Main.getFilePath() + folder + fileName + " dot sheet.pdf");

            ArrayList<String> list = new ArrayList<>(map.keySet());
            list.sort(nameComparator);

            for (String dotName : list) {
                if (dotName.replaceAll("[0-9]", "").equals(letter)) {
                    int i = 0;

                    PDPage page = new PDPage();
                    doc.addPage(page);

                    PDFont font = PDType1Font.HELVETICA_BOLD;
                    PDPageContentStream contentStream = new PDPageContentStream(doc, page);
                    contentStream.beginText();
                    contentStream.setFont(font, 10.0f);
                    contentStream.newLineAtOffset(10, page.getMediaBox().getHeight() - 20);
                    contentStream.showText(Main.getState().getCurrentFileName().substring(0,
                            Main.getState().getCurrentFileName().length() - 6));
                    contentStream.endText();

                    contentStream.beginText();
                    contentStream.setFont(font, 12.0f);
                    contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.3f,
                            page.getMediaBox().getHeight() - 20);
                    contentStream.showText(dotName);
                    contentStream.endText();

                    contentStream.beginText();
                    contentStream.setFont(font, 10.0f);
                    contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.6f,
                            page.getMediaBox().getHeight() - 20);
                    contentStream.showText("Name: ______________________________");
                    contentStream.endText();
                    contentStream.close();

                    float margin = 10;
                    float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
                    float yStartNewPage = page.getMediaBox().getHeight() - (3 * margin);
                    //noinspection UnnecessaryLocalVariable
                    float yStart = yStartNewPage;
                    float bottomMargin = 70;

                    BaseTable table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin,
                            doc, page, true, true);
                    //Create Header row
                    Row<PDPage> headerRow = table.createRow(15f);
                    Cell<PDPage> headerCell = headerRow.createCell(100 / 7f, "Set #");
                    headerCell.setAlign(HorizontalAlignment.CENTER);
                    headerCell.setFillColor(HEADER_COLOR);
                    headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell);
                    headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell);

                    table.addHeaderRow(headerRow);
                    for (int pageNum : new TreeSet<>(map.get(dotName).keySet())) {
                        String text = map.get(dotName).get(pageNum);
                        String[] lines = text.split("\\n");
                        String line1 = lines[0].replace("Horizontal - ", "");
                        String line2 = lines[1].replace("Vertical - ", "");

                        Row<PDPage> row = table.createRow(10f);
                        Cell<PDPage> cell = row.createCell(100 / 7f, pageNum + "");
                        cell.setAlign(HorizontalAlignment.CENTER);
                        cell.setFillColor(openingSets.contains(pageNum) ? OPENING_SET_COLOR : NORMAL_COLOR);
                        row.createCell(300 / 7f, line1).copyCellStyle(cell);
                        row.createCell(300 / 7f, line2).copyCellStyle(cell);

                        if (++i >= 35) {
                            table.draw();
                            page = new PDPage();
                            doc.addPage(page);
                            table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc,
                                    page, true, true);
                            //Create Header row
                            headerRow = table.createRow(15f);
                            headerCell = headerRow.createCell(100 / 7f, "Set #");
                            headerCell.setAlign(HorizontalAlignment.CENTER);
                            headerCell.setFillColor(HEADER_COLOR);
                            headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell);
                            headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell);
                            table.addHeaderRow(headerRow);

                            i -= 35;
                        }
                    }
                    table.draw();

                }
            }
            if (doc.getNumberOfPages() > 0)
                doc.save(f);
            else
                doc.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (doc != null)
            doc.close();
    }
    printing = false;
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String/*from   w  w w . j a  va 2  s  .co  m*/
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImage(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    if (imageFile != null) {
        imageFile.delete();
    }
    return pdfFile;
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String/*from  w  w w .java2s. c  o m*/
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImageNoDelete(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    return pdfFile;
}

From source file:com.foc.vaadin.gui.pdfGenerator.FocXmlPDFParser.java

License:Apache License

@Override
public PDPageContentStream getPDPageContentStream() {
    if (contentStream == null) {
        try {// w  ww .j  a va2  s  .  c  om
            contentStream = new PDPageContentStream(getPDDocument(), getPDPage());
        } catch (Exception e) {
            Globals.logException(e);
        }
    }
    return contentStream;
}