Example usage for com.itextpdf.text Document getPageSize

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

Introduction

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

Prototype


public Rectangle getPageSize() 

Source Link

Document

Gets the pagesize.

Usage

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.//  www  .  j  a v  a2s  . com
 * @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.fhaes.neofhchart.PDFExportOptionsDialog.java

License:Open Source License

/**
 * Performs the export operation using the currentChart as the source.
 * //from w  w  w  .  j  ava2 s .  co  m
 * @return true if the operation completed successfully, false otherwise
 */
private boolean doExportToPDF() {

    boolean completedSuccessfully = false;

    if (currentChart != null) {
        log.debug("Exporting to PDF...");
        Document document = null;

        if (cboPaperSize.getSelectedItem() instanceof Rectangle) {
            Rectangle rect = (Rectangle) cboPaperSize.getSelectedItem();

            if (radLandscape.isSelected()) {
                rect = rect.rotate();
            }

            document = new Document(rect, 10, 10, 10, 10);
        } else {
            Rectangle rect = new Rectangle(currentChart.getTotalWidth(), currentChart.getTotalHeight());
            document = new Document(rect, 10, 10, 10, 10);
        }

        try {
            currentChart.setVisibilityOfNoExportElements(false);

            PdfWriter writer = PdfWriter.getInstance(document,
                    new FileOutputStream(outputFile.getAbsolutePath()));
            document.open();

            int width = (int) document.getPageSize().getWidth();
            int height = (int) document.getPageSize().getHeight();

            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate template = cb.createTemplate(width, height);

            @SuppressWarnings("deprecation")
            Graphics2D g2 = template.createGraphics(width, height);

            PrintTranscoder prm = new PrintTranscoder();
            TranscoderInput ti = new TranscoderInput(currentChart.getSVGDocument());
            prm.transcode(ti, null);

            PageFormat pg = new PageFormat();
            Paper pp = new Paper();
            pp.setSize(width, height);
            pp.setImageableArea(0, 0, width, height);
            pg.setPaper(pp);
            prm.print(g2, pg, 0);
            g2.dispose();

            ImgTemplate img = new ImgTemplate(template);
            document.add(img);

            completedSuccessfully = true;
        } catch (DocumentException e) {
            System.err.println(e);
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            currentChart.setVisibilityOfNoExportElements(true);
        }

        document.close();
    }

    return completedSuccessfully;
}

From source file:org.ganttproject.impex.htmlpdf.itext.ThemeImpl.java

License:GNU General Public License

private PdfPTable createColontitleTable(String topLeft, String topRight, String bottomLeft,
        String bottomRight) {/*from   ww w. j  a  v  a  2s.c om*/
    PdfPTable head = new PdfPTable(2);
    {
        PdfPCell cell = new PdfPCell();
        cell.setBorder(Rectangle.NO_BORDER);
        Paragraph p = new Paragraph(topLeft, getSansRegularBold(18));
        p.setAlignment(Paragraph.ALIGN_LEFT);
        // colontitle.setLeading(0);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        // cell.setPaddingLeft(2);
        cell.setPaddingBottom(6);
        cell.setPhrase(p);
        head.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setBorder(Rectangle.NO_BORDER);
        Paragraph p = new Paragraph(topRight, getSansRegularBold(10));
        p.setAlignment(Paragraph.ALIGN_RIGHT);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setPaddingBottom(6);
        cell.setPhrase(p);
        head.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setPaddingLeft(3);
        cell.setPaddingTop(2);
        cell.setPaddingBottom(6);
        cell.setBorder(Rectangle.TOP);
        cell.setBorderWidthTop(2);
        cell.setBorderColor(SORTAVALA_GREEN);
        Paragraph p = new Paragraph(bottomLeft, getSansRegularBold(18));
        p.setAlignment(Paragraph.ALIGN_LEFT);
        p.setExtraParagraphSpace(0);
        p.setIndentationLeft(0);
        p.setSpacingBefore(0);
        cell.setPhrase(p);
        // cell.addElement(p);
        head.addCell(cell);
    }
    {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setPaddingTop(2);
        cell.setPaddingBottom(6);
        cell.setBorder(Rectangle.TOP);
        cell.setBorderWidthTop(2);
        cell.setBorderColor(SORTAVALA_GREEN);
        Paragraph p = new Paragraph(bottomRight, getSansRegularBold(10));
        p.setAlignment(Paragraph.ALIGN_RIGHT);
        cell.setPhrase(p);
        head.addCell(cell);
    }
    final Document document = myDoc;
    Rectangle page = document.getPageSize();
    head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
    return head;
}

From source file:org.ganttproject.impex.htmlpdf.itext.ThemeImpl.java

License:GNU General Public License

private void writeColontitle(String topLeft, String topRight, String bottomLeft, String bottomRight) {
    final Document document = myDoc;
    final PdfWriter writer = myWriter;
    Rectangle page = document.getPageSize();
    PdfPTable colontitleTable = createColontitleTable(topLeft, topRight, bottomLeft, bottomRight);
    colontitleTable.writeSelectedRows(0, -1, document.leftMargin(),
            page.getHeight() - document.topMargin() + colontitleTable.getTotalHeight(),
            writer.getDirectContent());//  w  ww  .j  a v a2s . com

}

From source file:org.jaqpot.core.service.data.ReportService.java

public void report2PDF(Report report, OutputStream os) {

    Document document = new Document();
    document.setPageSize(PageSize.A4);//ww w  . j  ava2 s  .co m
    document.setMargins(50, 45, 80, 40);
    document.setMarginMirroring(false);

    try {
        PdfWriter writer = PdfWriter.getInstance(document, os);
        TableHeader event = new TableHeader();
        writer.setPageEvent(event);

    } catch (DocumentException ex) {
        throw new InternalServerErrorException(ex);
    }

    document.open();

    /** setup fonts for pdf */
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 9, Font.ITALIC);
    Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC);
    Font paragraphFontBold = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
    Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
    Font tableFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);

    /** print link to jaqpot*/
    Chunk chunk = new Chunk(
            "This report has been automatically created by the JaqpotQuatro report service. Click here to navigate to our official webpage",
            ffont);
    chunk.setAnchor("http://www.jaqpot.org");

    Paragraph paragraph = new Paragraph(chunk);
    paragraph.add(Chunk.NEWLINE);

    Chapter chapter = new Chapter(paragraph, 1);
    chapter.setNumberDepth(0);

    /** get title */
    String title = null;
    if (report.getMeta() != null && report.getMeta().getTitles() != null
            && !report.getMeta().getTitles().isEmpty())
        title = report.getMeta().getTitles().iterator().next();

    /** print title aligned centered in page */
    if (title == null)
        title = "Report";
    chunk = new Chunk(title, chapterFont);
    paragraph = new Paragraph(chunk);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.add(Chunk.NEWLINE);
    paragraph.add(Chunk.NEWLINE);

    chapter.add(paragraph);

    /** report Description */
    if (report.getMeta() != null && report.getMeta().getDescriptions() != null
            && !report.getMeta().getDescriptions().isEmpty()
            && !report.getMeta().getDescriptions().toString().equalsIgnoreCase("null")) {
        paragraph = new Paragraph();
        paragraph.add(new Chunk("Description: ", paragraphFontBold));
        paragraph.add(new Chunk(report.getMeta().getDescriptions().toString().replaceAll(":http", ": http"),
                paragraphFont));
        chapter.add(paragraph);
        chapter.add(Chunk.NEWLINE);
    }

    /** report model, algorithm and/or dataset id */
    if (report.getMeta() != null && report.getMeta().getHasSources() != null
            && !report.getMeta().getHasSources().isEmpty() && !report.getMeta().getDescriptions().isEmpty()
            && !report.getMeta().getDescriptions().toString().equalsIgnoreCase("null")) {
        Iterator<String> sources = report.getMeta().getHasSources().iterator();
        sources.forEachRemaining(o -> {
            if (o != null) {
                String[] source = o.split("/");
                if (source[source.length - 2].trim().equals("model")
                        || source[source.length - 2].trim().equals("algorithm")
                        || source[source.length - 2].trim().equals("dataset")) {
                    Paragraph paragraph1 = new Paragraph();
                    paragraph1.add(new Chunk(source[source.length - 2].substring(0, 1).toUpperCase()
                            + source[source.length - 2].substring(1) + ": ", paragraphFontBold));
                    paragraph1.add(new Chunk(source[source.length - 1], paragraphFont));
                    chapter.add(paragraph1);
                    chapter.add(Chunk.NEWLINE);
                }
            }
        });
    }

    /** report single calculations */
    report.getSingleCalculations().forEach((key, value) -> {
        Paragraph paragraph1 = new Paragraph();
        paragraph1 = new Paragraph();
        paragraph1.add(new Chunk(key + ": ", paragraphFontBold));
        paragraph1.add(new Chunk(value.toString().trim().replaceAll(" +", " "), paragraphFont));
        chapter.add(paragraph1);
        chapter.add(Chunk.NEWLINE);
    });

    /** report date of completion */
    if (report.getMeta() != null && report.getMeta().getDate() != null) {
        Paragraph paragraph1 = new Paragraph();
        paragraph1.add(new Chunk("Procedure completed on: ", paragraphFontBold));
        paragraph1.add(new Chunk(report.getMeta().getDate().toString(), paragraphFont));
        chapter.add(paragraph1);
        chapter.add(Chunk.NEWLINE);
    }

    try {
        document.add(chapter);
    } catch (DocumentException ex) {
        throw new InternalServerErrorException(ex);
    }

    Integer chapterNumber = 0;

    /** report all_data */
    for (Entry<String, ArrayCalculation> entry : report.getArrayCalculations().entrySet()) {
        String label = entry.getKey();
        ArrayCalculation ac = entry.getValue();
        PdfPTable table = new PdfPTable(ac.getColNames().size() + 1);
        for (Entry<String, List<Object>> row : ac.getValues().entrySet()) {

            try {
                XMLWorkerHelper.getInstance().parseXHtml(w -> {
                    if (w instanceof WritableElement) {
                        List<Element> elements = ((WritableElement) w).elements();
                        for (Element element : elements) {
                            PdfPCell pdfCell = new PdfPCell();
                            pdfCell.addElement(element);
                            table.addCell(pdfCell);
                        }
                    }
                }, new StringReader(row.getKey()));
            } catch (IOException e) {
                e.printStackTrace();
            }

            for (Object o : row.getValue()) {
                table.addCell(o.toString());
            }
            table.completeRow();
        }
        try {
            Chunk tableChunk = new Chunk(label, tableFont);
            Chapter tableChapter = new Chapter(new Paragraph(tableChunk), ++chapterNumber);
            tableChapter.add(Chunk.NEWLINE);
            tableChapter.add(table);
            document.newPage();
            document.add(tableChapter);
        } catch (DocumentException ex) {
            throw new InternalServerErrorException(ex);
        }
    }

    /** report plots */
    for (Entry<String, String> entry : report.getFigures().entrySet()) {
        try {
            byte[] valueDecoded = Base64.decodeBase64(entry.getValue());
            Image l = Image.getInstance(valueDecoded);
            document.newPage();
            //image starts at the half's half of pdf page
            l.setAbsolutePosition(0, (document.getPageSize().getHeight() / 2 / 2));
            l.scaleToFit(document.getPageSize());

            Chunk tableChunk = new Chunk(entry.getKey(), tableFont);
            Chapter tableChapter = new Chapter(new Paragraph(tableChunk), ++chapterNumber);
            tableChapter.add(l);
            document.add(tableChapter);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
    document.close();
}

From source file:org.openscience.cdk.applications.taverna.renderer.DrawPDF.java

License:Open Source License

public static void drawMoleculesAsPDF(List<IAtomContainer> molecules, File file) throws Exception {
    Document pdf = new Document();
    PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(file));
    pdf.open();//from  w w  w .  ja v a  2s.  c  om
    Paragraph para = new Paragraph();
    Font font = FontFactory.getFont(FontFactory.HELVETICA, 24);
    para.setFont(font);
    para.setAlignment(Element.ALIGN_CENTER);
    para.add("CDK-Taverna 2.0");
    pdf.add(para);
    para = new Paragraph();
    font = FontFactory.getFont(FontFactory.HELVETICA, 12);
    para.setFont(font);
    para.setAlignment(Element.ALIGN_CENTER);
    para.add("The open-source chemo-/bioinformatics workflow solution\n\n\n");
    pdf.add(para);
    PdfPTable table = new PdfPTable(ncol);
    for (IAtomContainer molecule : molecules) {
        PdfPCell cell = new PdfPCell();
        cell.disableBorderSide(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
        BufferedImage image = Draw2DStructure.drawMolecule(molecule, (int) pdf.getPageSize().getWidth(), height,
                0.95);
        java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(image.getSource());
        cell.addElement(Image.getInstance(awtImage, null));
        table.addCell(cell);
        cell = new PdfPCell();
        cell.disableBorderSide(PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
        para = new Paragraph();
        font = FontFactory.getFont(FontFactory.HELVETICA, 12);
        para.setFont(font);
        para.add("\n");
        for (Entry<Object, Object> entry : molecule.getProperties().entrySet()) {
            try {
                String key = String.valueOf(entry.getKey());
                String value = String.valueOf(entry.getValue());
                para.add(key + ":\n" + value + "\n\n");
            } catch (Exception e) {
                // Not a String entry --> skip
            }
        }
        cell.addElement(para);
        table.addCell(cell);
    }
    pdf.add(table);
    pdf.close();
}

From source file:org.orbisgis.core.ui.plugins.editors.mapEditor.ExportMapAsPDFPlugIn.java

License:Open Source License

public void save(File outputFile, Scale scale, BufferedImage img, Envelope envelope, ILayer layer) {
    int width = img.getWidth();
    int height = img.getHeight();
    Document document = new Document(PageSize.A4.rotate());
    EditorManager em = Services.getService(EditorManager.class);
    MapEditorPlugIn mapEditor = (MapEditorPlugIn) em.getActiveEditor();
    MapContext mapContext = (MapContext) mapEditor.getElement().getObject();

    try {//  www  . ja  v a2  s  .  com

        Renderer r = new Renderer();

        if (outputFile.getName().toLowerCase().endsWith("pdf")) { //$NON-NLS-1$

            FileOutputStream fos = new FileOutputStream(outputFile);

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

            document.open();

            float pageWidth = document.getPageSize().getWidth();
            float pageHeight = document.getPageSize().getHeight();

            // Add the north
            final java.net.URL url = IconLoader.getIconUrl("simplenorth.png"); //$NON-NLS-1$

            PdfContentByte cb = writer.getDirectContent();

            PdfTemplate templateMap = cb.createTemplate(pageWidth, pageHeight);

            PdfTemplate templateLegend = cb.createTemplate(150, pageHeight);

            PdfTemplate templateScale = cb.createTemplate(pageWidth, 50);

            Graphics2D g2dLegend = templateLegend.createGraphicsShapes(150, pageHeight);

            Graphics2D g2dMap = templateMap.createGraphicsShapes(pageWidth, pageHeight);

            Graphics2D g2dScale = templateScale.createGraphicsShapes(pageWidth, 50);

            g2dMap.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            r.draw(g2dMap, width, height, envelope, layer, new NullProgressMonitor());

            ILayer[] layers = mapContext.getLayerModel().getLayersRecursively();

            g2dLegend.setColor(Color.BLACK);
            g2dLegend.drawRect(0, 0, 150, (int) pageHeight);

            g2dLegend.setColor(Color.white);
            g2dLegend.fillRect(0, 0, 150, (int) pageHeight);

            g2dLegend.setColor(Color.BLACK);
            int maxHeight = 30;

            g2dLegend.translate(10, 10);
            g2dLegend.drawString(I18N.getString("orbisgis.org.orbisgis.ui.map.exportMapAsPDFPlugIn.legend"), 0, //$NON-NLS-1$
                    10);

            for (int i = 0; i < layers.length; i++) {
                g2dLegend.translate(0, maxHeight + 10);
                maxHeight = 0;
                if (layers[i].isVisible()) {
                    Legend[] legends = layers[i].getRenderingLegend();
                    g2dLegend.drawString(layers[i].getName(), 0, 0);
                    for (int j = 0; j < legends.length; j++) {
                        Legend vectorLegend = legends[j];
                        vectorLegend.drawImage(g2dLegend);
                        int[] size = vectorLegend.getImageSize(g2dLegend);
                        if (size[1] > maxHeight) {
                            maxHeight = size[1];
                        }
                        g2dLegend.translate(0, 20);
                    }
                }
            }

            g2dScale.translate(150, 0);
            g2dScale.setColor(Color.BLACK);
            g2dScale.drawRect(0, 0, (int) pageWidth, 50);

            g2dScale.setColor(Color.white);
            g2dScale.fillRect(0, 0, (int) pageWidth, 50);

            g2dScale.setColor(Color.BLACK);

            g2dScale.translate(30, 10);
            // draw scale
            if (scale != null) {
                scale.drawScale(g2dScale, 90);
            }

            BufferedImage image = ImageIO.read(url);

            AffineTransform tx = new AffineTransform();
            tx.scale(0.5, 0.5);

            AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
            image = op.filter(image, null);

            g2dScale.drawImage(image, 200, 0, null);

            g2dMap.dispose();
            g2dLegend.dispose();
            g2dScale.dispose();

            cb.addTemplate(templateMap, 0, 0);
            cb.addTemplate(templateLegend, 0, 0);
            cb.addTemplate(templateScale, 0, 0);

            JOptionPane.showMessageDialog(UIFactory.getMainFrame(),
                    I18N.getString("orbisgis.core.file.fileSaved")); //$NON-NLS-1$
        }

    } catch (FileNotFoundException e) {
        ErrorMessages.error(ErrorMessages.CannotWriteOnDisk, e);
    } catch (DocumentException e) {
        ErrorMessages.error(ErrorMessages.CannotWritePDF, e);
    } catch (Exception e) {
        ErrorMessages.error(ErrorMessages.CannotWritePDF, e);
    }

    document.close();

}

From source file:org.saiku.web.export.PdfReport.java

License:Apache License

public byte[] pdf(QueryResult qr, String svg) throws Exception {

    int resultWidth = qr != null && qr.getCellset() != null && qr.getCellset().size() > 0
            ? qr.getCellset().get(0).length
            : 0;//w w  w  .j  a  va 2  s .  c  o m
    if (resultWidth == 0) {
        throw new SaikuServiceException("Cannot convert empty result to PDF");
    }
    Rectangle size = PageSize.A4.rotate();
    if (resultWidth > 8) {
        size = PageSize.A3.rotate();
    }
    if (resultWidth > 16) {
        size = PageSize.A2.rotate();
    }
    if (resultWidth > 32) {
        size = PageSize.A1.rotate();
    }
    if (resultWidth > 64) {
        size = PageSize.A0.rotate();
    }

    Document document = new Document(size, 15, 15, 10, 10);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    populatePdf(document, writer, qr);

    // do we want to add a svg image?
    if (StringUtils.isNotBlank(svg)) {
        document.newPage();
        StringBuffer s1 = new StringBuffer(svg);
        if (!svg.startsWith("<svg xmlns=\"http://www.w3.org/2000/svg\" ")) {
            s1.insert(s1.indexOf("<svg") + 4, " xmlns='http://www.w3.org/2000/svg'");
        }

        String t = "<?xml version='1.0' encoding='ISO-8859-1'" + " standalone='no'?>" + s1.toString();
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        cb.concatCTM(1.0f, 0, 0, 1.0f, 36, 0);
        float width = document.getPageSize().getWidth() - 20;
        float height = document.getPageSize().getHeight() - 20;
        Graphics2D g2 = cb.createGraphics(width, height);
        //g2.rotate(Math.toRadians(-90), 100, 100);
        PrintTranscoder prm = new PrintTranscoder();
        TranscoderInput ti = new TranscoderInput(new StringReader(t));
        prm.transcode(ti, null);
        PageFormat pg = new PageFormat();
        Paper pp = new Paper();
        pp.setSize(width, height);
        pp.setImageableArea(5, 5, width, height);
        pg.setPaper(pp);
        prm.print(g2, pg, 0);
        g2.dispose();
        cb.restoreState();
    }

    document.close();
    return baos.toByteArray();
}

From source file:pdfMaker.MakePdfFile.java

MakePdfFile(String text1, String text2, String text3) throws IOException, DocumentException, RuntimeException {

    // // w w w  .j  av  a  2s.c o m
    url = text1;

    Document document = null;
    String fileDir = "TEST_MAT.pdf";
    // step 1
    document = new Document(PageSize.A4, 20, 20, 20, 20);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileDir));

    // step 3
    document.open();
    // step 4
    PdfContentByte cb = writer.getDirectContent();

    Image image = ZxingUti.getQRCode(url); //  SHIFT_JIS
    com.itextpdf.text.Image iTextImage = com.itextpdf.text.Image.getInstance(image, null);

    // http://d.hatena.ne.jp/MoonMtLab/20130920/1379626380
    //Image??
    com.itextpdf.text.Image img = iTextImage;

    //??()
    img.setAbsolutePosition(document.getPageSize().getWidth() - 30, document.getPageSize().getHeight() - 30);
    System.out.println(document.getPageSize().getWidth());
    System.out.println(document.getPageSize().getHeight());
    //?
    img.scaleAbsolute(30, 30);

    //PdfContentByte??
    PdfContentByte pdfContentByte = writer.getDirectContent();

    //???
    pdfContentByte.addImage(img);

    /* 
     writer.setEncryption("Hello".getBytes(), "World".getBytes(),
     PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128);
     // 
     */
    document.close();

}

From source file:sc.emea.tools.image.Tiff2PDF.java

License:Apache License

public static void main(String args[]) {

    int page_counter = 0;

    try {//w w  w  .ja  v  a  2  s . c  om

        // Read the Tiff File
        FileList myFileList = new FileList("C:\\DEV\\Eclipse-Workspace\\Luna-J\\Tiff2PdfConverter\\TIFF\\");
        myFileList.setFilterPreMiddleSuffix("", "", ".tiff");
        myFileList.sort(ComparableAttribute.dateLastModified, SortingDirection.asc);

        File[] myTiffFileFiles = myFileList.getFilesArray();

        if (myTiffFileFiles.length < 1)
            return;
        else
            for (File file : myTiffFileFiles)
                System.out.println(file.getName());

        Document myDocument = new Document();
        myDocument.setMargins(0, 0, 0, 0);
        PdfWriter.getInstance(myDocument,
                new FileOutputStream("C:\\DEV\\Eclipse-Workspace\\Luna-J\\Tiff2PdfConverter\\PDF\\test.pdf"));
        myDocument.open();

        RandomAccessSourceFactory rasFactory = new RandomAccessSourceFactory();

        for (File file : myTiffFileFiles) {

            FileInputStream _fis = new FileInputStream(file.getAbsolutePath());

            RandomAccessSource _ra_source = rasFactory.createSource(_fis);
            RandomAccessFileOrArray _ra_file = new RandomAccessFileOrArray(_ra_source);

            int numberOfPages = TiffImage.getNumberOfPages(_ra_file);
            for (int i = 1; i <= numberOfPages; i++) {
                Image _image = TiffImage.getTiffImage(_ra_file, i);
                _image.scaleAbsolute(myDocument.getPageSize());
                myDocument.add(_image);
                page_counter++;
            }

        }
        myDocument.close();
        System.out.println("Tiff to PDF conversion completed for " + page_counter);

    } catch (Exception i1) {
        i1.printStackTrace();
    }
}