Java Code Examples for com.lowagie.text.pdf.PdfTemplate#createGraphics()

The following examples show how to use com.lowagie.text.pdf.PdfTemplate#createGraphics() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Image.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Gets an instance of a Image from a java.awt.Image. The image is added as a JPEG with a user
 * defined quality.
 *
 * @param cb the <CODE>PdfContentByte</CODE> object to which the image will be added
 * @param awtImage the <CODE>java.awt.Image</CODE> to convert
 * @param quality a float value between 0 and 1
 * @return an object of type <CODE>PdfTemplate</CODE>
 * @throws BadElementException on error
 * @throws IOException
 */
public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
	java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage, 0, 0, -1, -1, true);
	try {
		pg.grabPixels();
	} catch (InterruptedException e) {
		throw new IOException("java.awt.Image Interrupted waiting for pixels!");
	}
	if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
		throw new IOException("java.awt.Image fetch aborted or errored");
	}
	int w = pg.getWidth();
	int h = pg.getHeight();
	PdfTemplate tp = cb.createTemplate(w, h);
	Graphics2D g2d = tp.createGraphics(w, h, true, quality);
	g2d.drawImage(awtImage, 0, 0, null);
	g2d.dispose();
	return getInstance(tp);
}
 
Example 2
Source File: Image.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets an instance of a Image from a java.awt.Image.
 * The image is added as a JPEG with a user defined quality.
 *
 * @param cb
 *            the <CODE>PdfContentByte</CODE> object to which the image will be added
 * @param awtImage
 *            the <CODE>java.awt.Image</CODE> to convert
 * @param quality
 *            a float value between 0 and 1
 * @return an object of type <CODE>PdfTemplate</CODE>
 * @throws BadElementException
 *             on error
 * @throws IOException
 */
public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
    java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage,
            0, 0, -1, -1, true);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
        throw new IOException(
                "java.awt.Image Interrupted waiting for pixels!");
    }
    if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
        throw new IOException("java.awt.Image fetch aborted or errored");
    }
    int w = pg.getWidth();
    int h = pg.getHeight();
    PdfTemplate tp = cb.createTemplate(w, h);
    Graphics2D g2d = tp.createGraphics(w, h, true, quality);
    g2d.drawImage(awtImage, 0, 0, null);
    g2d.dispose();
    return getInstance(tp);
}
 
Example 3
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected PdfTemplate transSVG( String svgPath, byte[] svgData, float x,
		float y, float height, float width, String helpText )
		throws IOException, DocumentException
{
	PdfTemplate template = contentByte.createTemplate( width, height );
	Graphics2D g2D = template.createGraphics( width, height );

	PrintTranscoder transcoder = new PrintTranscoder( );
	if ( null != svgData && svgData.length > 0 )
	{
		transcoder.transcode( new TranscoderInput(
				new ByteArrayInputStream( svgData ) ), null );
	}
	else if ( null != svgPath )
	{
		transcoder.transcode( new TranscoderInput( svgPath ), null );
	}
	PageFormat pg = new PageFormat( );
	Paper p = new Paper( );
	p.setSize( width, height );
	p.setImageableArea( 0, 0, width, height );
	pg.setPaper( p );
	transcoder.print( g2D, pg, 0 );
	g2D.dispose( );
	return template;
}
 
Example 4
Source File: JFreeChartTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
  * Converts a JFreeChart to PDF syntax.
  * @param filename	the name of the PDF file
  * @param chart		the JFreeChart
  * @param width		the width of the resulting PDF
  * @param height	the height of the resulting PDF
  */
 public static void convertToPdf(JFreeChart chart, int width, int height, String filename) {
 	// step 1
 	Document document = new Document(new Rectangle(width, height));
 	try {
 		// step 2
 		PdfWriter writer;
writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream(filename));
// step 3
 		document.open();
 		// step 4
 		PdfContentByte cb = writer.getDirectContent();
 		PdfTemplate tp = cb.createTemplate(width, height);
 		Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
 		Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
 		chart.draw(g2d, r2d);
 		g2d.dispose();
 		tp.sanityCheck();
 		cb.addTemplate(tp, 0, 0);
 		cb.sanityCheck();
 	}
 	catch(DocumentException de) {
 		de.printStackTrace();
 	}
 	catch (FileNotFoundException e) {
 		e.printStackTrace();
 	}
 	// step 5
 	document.close();
 }
 
Example 5
Source File: PdfExportHelper.java    From mdw with Apache License 2.0 5 votes vote down vote up
private void printDiagram(DocWriter writer, Chapter chapter, Process process,
        Rectangle pageSize) throws Exception {
    ProcessCanvas canvas = new ProcessCanvas(project, process);
    canvas.prepare();

    Dimension size = new PngProcessExporter(project).getDiagramSize(process);
    // create a template and a Graphics2D object that corresponds with it
    int w;
    int h;
    float scale;
    if ((float) size.width < pageSize.getWidth() * 0.8
            && (float) size.height < pageSize.getHeight() * 0.8) {
        w = size.width + 36;
        h = size.height + 36;
        scale = -1f;
    }
    else {
        scale = pageSize.getWidth() * 0.8f / (float) size.width;
        if (scale > pageSize.getHeight() * 0.8f / (float) size.height)
            scale = pageSize.getHeight() * 0.8f / (float) size.height;
        w = (int) (size.width * scale) + 36;
        h = (int) (size.height * scale) + 36;
    }

    PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
    PdfTemplate tp = cb.createTemplate(w, h);
    Graphics2D g2 = tp.createGraphics(w, h);
    if (scale > 0)
        g2.scale(scale, scale);
    tp.setWidth(w);
    tp.setHeight(h);
    canvas.paintComponent(g2);
    g2.dispose();
    Image img = new ImgTemplate(tp);
    chapter.add(img);
    canvas.dispose();
}
 
Example 6
Source File: ImageExporter.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
private void exportVectorGraphics(String formatName, File outputFile) throws ImageExportException {
	Component component = printableComponent.getExportComponent();
	int width = component.getWidth();
	int height = component.getHeight();
	try (FileOutputStream fs = new FileOutputStream(outputFile)) {
		switch (formatName) {
			case PDF:
				// create pdf document with slightly increased width and height
				// (otherwise the image gets cut off)
				Document document = new Document(new Rectangle(width + 5, height + 5));
				PdfWriter writer = PdfWriter.getInstance(document, fs);
				document.open();
				PdfContentByte cb = writer.getDirectContent();
				PdfTemplate tp = cb.createTemplate(width, height);
				Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
				component.print(g2);
				g2.dispose();
				cb.addTemplate(tp, 0, 0);
				document.close();
				break;
			case SVG:
				exportFreeHep(component, fs, new SVGGraphics2D(fs, new Dimension(width, height)));
				break;
			case EPS:
				exportFreeHep(component, fs, new PSGraphics2D(fs, new Dimension(width, height)));
				break;
			default:
				// cannot happen
				break;
		}
	} catch (Exception e) {
		throw new ImageExportException(I18N.getMessage(I18N.getUserErrorMessagesBundle(),
				"error.image_export.export_failed"), e);
	}
}
 
Example 7
Source File: MapperFrameOld.java    From beast-mcmc with GNU Lesser General Public License v2.1 5 votes vote down vote up
public final void doExportPDF() {
        FileDialog dialog = new FileDialog(this,
                "Export PDF Image...",
                FileDialog.SAVE);

        dialog.setVisible(true);
        if (dialog.getFile() != null) {
            File file = new File(dialog.getDirectory(), dialog.getFile());

            Rectangle2D bounds = mapperPanel.getExportableComponent().getBounds();
            Document document = new Document(new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
            try {
                // step 2
                PdfWriter writer;
                writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
                document.open();
// step 4
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
                Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper());
                mapperPanel.getExportableComponent().print(g2d);
                g2d.dispose();
                cb.addTemplate(tp, 0, 0);
            }
            catch (DocumentException de) {
                JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de,
                        "Export PDF Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e,
                        "Export PDF Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            document.close();
        }
    }
 
Example 8
Source File: ExportHighCharts.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void transformSVGIntoPDF(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException {

		Rectangle pageSize = PageSize.A4;
		Document document = new Document(pageSize);
		int orientation = PageFormat.PORTRAIT;
		try {
			PdfWriter writer = PdfWriter.getInstance(document, outputStream);
			document.open();

			double a4WidthInch = 8.26771654; // Equals 210mm
			double a4HeightInch = 11.6929134; // Equals 297mm

			Paper paper = new Paper();
			// 72 DPI
			paper.setSize((a4WidthInch * 72), (a4HeightInch * 72));
			// 1 inch margins
			paper.setImageableArea(72, 72, (a4WidthInch * 72 - 144), (a4HeightInch * 72 - 144));
			PageFormat pageFormat = new PageFormat();
			pageFormat.setPaper(paper);
			pageFormat.setOrientation(orientation);

			float width = ((float) pageFormat.getWidth());
			float height = ((float) pageFormat.getHeight());

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

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

			prm.print(g2, pageFormat, 0);
			g2.dispose();

			ImgTemplate img = new ImgTemplate(template);
			img.setWidthPercentage(100);
			img.setAlignment(Image.ALIGN_CENTER);

			document.add(img);

		} catch (DocumentException e) {
			logger.error("Error exporting Highcharts to PDF: " + e);
		}
		document.close();
	}
 
Example 9
Source File: CharacterSheet.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * @param path The path to save to.
 * @return {@code true} on success.
 */
public boolean saveAsPDF(Path path) {
    Set<Row> changed = expandAllContainers();
    try {
        PrintManager settings = mCharacter.getPageSettings();
        PageFormat   format   = settings != null ? settings.createPageFormat() : createDefaultPageFormat();
        float        width    = (float) format.getWidth();
        float        height   = (float) format.getHeight();

        adjustToPageSetupChanges(true);
        setPrinting(true);

        com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(new com.lowagie.text.Rectangle(width, height));
        try (OutputStream out = Files.newOutputStream(path)) {
            PdfWriter      writer  = PdfWriter.getInstance(pdfDoc, out);
            int            pageNum = 0;
            PdfContentByte cb;

            pdfDoc.open();
            cb = writer.getDirectContent();
            while (true) {
                PdfTemplate template = cb.createTemplate(width, height);
                Graphics2D  g2d      = template.createGraphics(width, height, new DefaultFontMapper());

                if (print(g2d, format, pageNum) == NO_SUCH_PAGE) {
                    g2d.dispose();
                    break;
                }
                if (pageNum != 0) {
                    pdfDoc.newPage();
                }
                g2d.setClip(0, 0, (int) width, (int) height);
                print(g2d, format, pageNum++);
                g2d.dispose();
                cb.addTemplate(template, 0, 0);
            }
            pdfDoc.close();
        }
        return true;
    } catch (Exception exception) {
        Log.error(exception);
        return false;
    } finally {
        setPrinting(false);
        closeContainers(changed);
    }
}
 
Example 10
Source File: VisualizePanelCharts2D.java    From KEEL with GNU General Public License v3.0 4 votes vote down vote up
private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this, "File " + nombre + " already exists. Do you want to replace it?",
                "Confirm", JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412,
                        new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}