com.lowagie.text.pdf.PdfTemplate Java Examples

The following examples show how to use com.lowagie.text.pdf.PdfTemplate. 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: OptionalContentTest.java    From itext2 with GNU Lesser General Public License v3.0 7 votes vote down vote up
/**
 * Demonstrates the use of layers.
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {
	// step 1: creation of a document-object
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step 2: creation of the writer
	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("optionalcontent.pdf"));
	writer.setPdfVersion(PdfWriter.VERSION_1_5);
	writer.setViewerPreferences(PdfWriter.PageModeUseOC);
	// step 3: opening the document
	document.open();
	// step 4: content
	PdfContentByte cb = writer.getDirectContent();
	Phrase explanation = new Phrase(
			"Automatic layers, form fields, images, templates and actions",
			new Font(Font.HELVETICA, 18, Font.BOLD, Color.red));
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50,
			650, 0);
	PdfLayer l1 = new PdfLayer("Layer 1", writer);
	PdfLayer l2 = new PdfLayer("Layer 2", writer);
	PdfLayer l3 = new PdfLayer("Layer 3", writer);
	PdfLayer l4 = new PdfLayer("Form and XObject Layer", writer);
	PdfLayerMembership m1 = new PdfLayerMembership(writer);
	m1.addMember(l2);
	m1.addMember(l3);
	Phrase p1 = new Phrase("Text in layer 1");
	Phrase p2 = new Phrase("Text in layer 2 or layer 3");
	Phrase p3 = new Phrase("Text in layer 3");
	cb.beginLayer(l1);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0f);
	cb.endLayer();
	cb.beginLayer(m1);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0);
	cb.endLayer();
	cb.beginLayer(l3);
	ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0);
	cb.endLayer();
	TextField ff = new TextField(writer, new Rectangle(200, 600, 300, 620),
			"field1");
	ff.setBorderColor(Color.blue);
	ff.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
	ff.setBorderWidth(TextField.BORDER_WIDTH_THIN);
	ff.setText("I'm a form field");
	PdfFormField form = ff.getTextField();
	form.setLayer(l4);
	writer.addAnnotation(form);
	Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR
			+ "pngnow.png");
	img.setLayer(l4);
	img.setAbsolutePosition(200, 550);
	cb.addImage(img);
	PdfTemplate tp = cb.createTemplate(100, 20);
	Phrase pt = new Phrase("I'm a template", new Font(Font.HELVETICA, 12,
			Font.NORMAL, Color.magenta));
	ColumnText.showTextAligned(tp, Element.ALIGN_LEFT, pt, 0, 0, 0);
	tp.setLayer(l4);
	tp.setBoundingBox(new Rectangle(0, -10, 100, 20));
	cb.addTemplate(tp, 200, 500);
	ArrayList<Object> state = new ArrayList<Object>();
	state.add("toggle");
	state.add(l1);
	state.add(l2);
	state.add(l3);
	state.add(l4);
	PdfAction action = PdfAction.setOCGstate(state, true);
	Chunk ck = new Chunk("Click here to toggle the layers", new Font(
			Font.HELVETICA, 18, Font.NORMAL, Color.yellow)).setBackground(
			Color.blue).setAction(action);
	ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(ck),
			250, 400, 0);
	cb.sanityCheck();

	// step 5: closing the document
	document.close();
}
 
Example #2
Source File: ImgTemplate.java    From MesquiteCore with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Creats an Image from a PdfTemplate.
 *
 * @param template the PdfTemplate
 * @throws BadElementException on error
 */
public ImgTemplate(PdfTemplate template) throws BadElementException{
    super((URL)null);
    if (template == null)
        throw new BadElementException("The template can not be null.");
    if (template.getType() == PdfTemplate.TYPE_PATTERN)
        throw new BadElementException("A pattern can not be used as a template to create an image.");
    type = IMGTEMPLATE;
    scaledHeight = template.getHeight();
    setTop(scaledHeight);
    scaledWidth = template.getWidth();
    setRight(scaledWidth);
    setTemplateData(template);
    plainWidth = width();
    plainHeight = height();
}
 
Example #3
Source File: ImgTemplate.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/** Creates an Image from a PdfTemplate.
 *
 * @param template the PdfTemplate
 * @throws BadElementException on error
 */
public ImgTemplate(PdfTemplate template) throws BadElementException{
    super((URL)null);
    if (template == null)
        throw new BadElementException("The template can not be null.");
    if (template.getType() == PdfTemplate.TYPE_PATTERN)
        throw new BadElementException("A pattern can not be used as a template to create an image.");
    type = IMGTEMPLATE;
    scaledHeight = template.getHeight();
    setTop(scaledHeight);
    scaledWidth = template.getWidth();
    setRight(scaledWidth);
    setTemplateData(template);
    plainWidth = getWidth();
    plainHeight = getHeight();
}
 
Example #4
Source File: ImgWMF.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/** Reads the WMF into a template.
 * @param template the template to read to
 * @throws IOException on error
 * @throws DocumentException on error
 */    
public void readWMF(PdfTemplate template) throws IOException, DocumentException {
    setTemplateData(template);
    template.setWidth(getWidth());
    template.setHeight(getHeight());
    InputStream is = null;
    try {
        if (rawData == null){
            is = url.openStream();
        }
        else{
            is = new java.io.ByteArrayInputStream(rawData);
        }
        MetaDo meta = new MetaDo(is, template);
        meta.readAll();
    }
    finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example #5
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 #6
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 #7
Source File: ImgTemplate.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Creates an Image from a PdfTemplate.
 *
 * @param template the PdfTemplate
 * @throws BadElementException on error
 */
public ImgTemplate(PdfTemplate template) throws BadElementException{
    super((URL)null);
    if (template == null)
        throw new BadElementException("The template can not be null.");
    if (template.getType() == PdfTemplate.TYPE_PATTERN)
        throw new BadElementException("A pattern can not be used as a template to create an image.");
    type = IMGTEMPLATE;
    scaledHeight = template.getHeight();
    setTop(scaledHeight);
    scaledWidth = template.getWidth();
    setRight(scaledWidth);
    setTemplateData(template);
    plainWidth = getWidth();
    plainHeight = getHeight();
}
 
Example #8
Source File: ImgWMF.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Reads the WMF into a template.
 * @param template the template to read to
 * @throws IOException on error
 * @throws DocumentException on error
 */    
public void readWMF(PdfTemplate template) throws IOException, DocumentException {
    setTemplateData(template);
    template.setWidth(getWidth());
    template.setHeight(getHeight());
    InputStream is = null;
    try {
        if (rawData == null){
            is = url.openStream();
        }
        else{
            is = new java.io.ByteArrayInputStream(rawData);
        }
        MetaDo meta = new MetaDo(is, template);
        meta.readAll();
    }
    finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example #9
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected void drawImage( PdfTemplate image, float imageX, float imageY,
		float height, float width, String helpText )
		throws DocumentException
{
	imageY = transformY( imageY, height );
	contentByte.saveState( );
	contentByte.concatCTM( 1, 0, 0, 1, imageX, imageY );
	float w = image.getWidth( );
	float h = image.getHeight( );
	contentByte.addTemplate( image, width / w, 0f / w, 0f / h, height / h,
			0f, 0f );
	if ( helpText != null )
	{
		showHelpText( imageX, imageY, width, height, helpText );
	}
	contentByte.restoreState( );
}
 
Example #10
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 #11
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private void createTotalPageTemplate( float x, float y, float width,
		float height, float scale )
{
	PdfTemplate template = null;
	if ( pageDevice.hasTemplate( scale ) )
	{
		template = pageDevice.getPDFTemplate( scale );
	}
	else
	{
		template = contentByte.createTemplate( width, height );
		pageDevice.setPDFTemplate( scale, template );
	}
	y = transformY( y, height );
	contentByte.saveState( );
	contentByte.addTemplate( template, x, y );
	contentByte.restoreState( );
}
 
Example #12
Source File: PDFRender.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public void setTotalPage( ITextArea totalPage )
{
	super.setTotalPage( totalPage );
	isTotalPage = true;
	HashMap<Float, PdfTemplate> map = ( (PDFPageDevice) pageDevice )
			.getTemplateMap( );
	if ( !map.isEmpty( ) )
	{
		float scaleCache = this.scale;
		for ( Entry<Float, PdfTemplate> e : map.entrySet( ) )
		{
			Float s = e.getKey( );
			PdfTemplate template = e.getValue( );
			if ( template != null )
			{
				this.scale = s.floatValue( );
				drawText( totalPage );
			}
		}
		this.scale = scaleCache;
	}
	isTotalPage = false;
}
 
Example #13
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 #14
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 #15
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 #16
Source File: PdfTimetableGridTable.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void addTextVertical(PdfPCell cell, String text, boolean bold) throws Exception  {
	if (text==null) return;
       if (text.indexOf("<span")>=0)
           text = text.replaceAll("</span>","").replaceAll("<span .*>", "");
       Font font = PdfFont.getFont(bold);
	BaseFont bf = font.getBaseFont();
	float width = bf.getWidthPoint(text, font.getSize());
	PdfTemplate template = iWriter.getDirectContent().createTemplate(2 * font.getSize() + 4, width);
	template.beginText();
	template.setColorFill(Color.BLACK);
	template.setFontAndSize(bf, font.getSize());
	template.setTextMatrix(0, 2);
	template.showText(text);
	template.endText();
	template.setWidth(width);
	template.setHeight(font.getSize() + 2);
	//make an Image object from the template
	Image img = Image.getInstance(template);
	img.setRotationDegrees(270);
	//embed the image in a Chunk
	Chunk ck = new Chunk(img, 0, 0);
	
	if (cell.getPhrase()==null) {
		cell.setPhrase(new Paragraph(ck));
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
	} else {
		cell.getPhrase().add(ck);
	}
}
 
Example #17
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 #18
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void drawTotalPage( String text, int textX, int textY, int width,
		int height, TextStyle textInfo, float scale )
{
	PdfTemplate template = pageDevice.getPDFTemplate( scale );
	if ( template != null )
	{
		PdfContentByte tempCB = this.contentByte;
		this.containerHeight = template.getHeight( );
		this.contentByte = template;
		drawText( text, textX, textY, width, height, textInfo );
		this.contentByte = tempCB;
		this.containerHeight = pageHeight;
	}
}
 
Example #19
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
protected void drawBackgroundImage( float x, float y, float width,
		float height, float imageWidth, float imageHeight, int repeat,
		String imageUrl, byte[] imageData, float offsetX, float offsetY )
		throws Exception
{
	contentByte.saveState( );
	clip( x, y, width, height );
	
	PdfTemplate image = null;
	if ( imageUrl != null )
	{
		if ( pageDevice.getImageCache( ).containsKey( imageUrl ) )
		{
			image = pageDevice.getImageCache( ).get( imageUrl );
		}
	}
	if ( image == null )
	{
		Image img = Image.getInstance( imageData );
		if ( imageHeight == 0 || imageWidth == 0 )
		{
			int resolutionX = img.getDpiX( );
			int resolutionY = img.getDpiY( );
			if ( 0 == resolutionX || 0 == resolutionY )
			{
				resolutionX = 96;
				resolutionY = 96;
			}
			imageWidth = img.getPlainWidth( ) / resolutionX * 72;
			imageHeight = img.getPlainHeight( ) / resolutionY * 72;
		}

		image = contentByte.createTemplate( imageWidth, imageHeight );
		image.addImage( img, imageWidth, 0, 0, imageHeight, 0, 0 );

		if ( imageUrl != null && image != null )
		{
			pageDevice.getImageCache( ).put( imageUrl, image );
		}
	}

	boolean xExtended = ( repeat & BackgroundImageInfo.REPEAT_X ) == BackgroundImageInfo.REPEAT_X;
	boolean yExtended = ( repeat & BackgroundImageInfo.REPEAT_Y ) == BackgroundImageInfo.REPEAT_Y;
	imageWidth = image.getWidth( );
	imageHeight = image.getHeight( );

	float originalX = offsetX;
	float originalY = offsetY;
	if ( xExtended )
	{
		while ( originalX > 0 )
			originalX -= imageWidth;
	}
	if ( yExtended )
	{
		while ( originalY > 0 )
			originalY -= imageHeight;
	}

	float startY = originalY;
	do
	{
		float startX = originalX;
		do
		{
			drawImage( image, x + startX, y + startY, imageWidth,
					imageHeight );
			startX += imageWidth;
		} while ( startX < width && xExtended );
		startY += imageHeight;
	} while ( startY < height && yExtended );
	contentByte.restoreState( );
}
 
Example #20
Source File: PDFPageDevice.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public HashMap<String, PdfTemplate> getImageCache( )
{
	return imageCache;
}
 
Example #21
Source File: PDFPageDevice.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public PdfTemplate getPDFTemplate( Float scale )
{
	return templateMap.get( scale );
}
 
Example #22
Source File: PDFPageDevice.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public HashMap<Float, PdfTemplate> getTemplateMap( )
{
	return templateMap;
}
 
Example #23
Source File: PDFPageDevice.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void setPDFTemplate( Float scale, PdfTemplate totalPageTemplate )
{
	templateMap.put( scale, totalPageTemplate );
}
 
Example #24
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
protected void drawImage( String imageId, byte[] imageData,
		String extension, float imageX, float imageY, float height,
		float width, String helpText, Map params ) throws Exception
{
	// Flash
	if ( FlashFile.isFlash( null, null, extension ) )
	{
		embedFlash( null, imageData, imageX, imageY, height, width,
				helpText, params );
		return;
	}

	// Cached Image
	PdfTemplate template = null;
	if ( imageId != null )
	{
		if ( pageDevice.getImageCache( ).containsKey( imageId ) )
		{
			template = pageDevice.getImageCache( ).get( imageId );
		}
		if ( template != null )
		{
			drawImage( template, imageX, imageY, height, width, helpText );
			return;
		}
	}

	// Not cached yet
	if ( SvgFile.isSvg( null, null, extension ) )
	{
		template = generateTemplateFromSVG( null, imageData, imageX,
				imageY, height, width, helpText );
	}
	else
	{
		// PNG/JPG/BMP... images:
		Image image = Image.getInstance( imageData );
		if ( imageId == null )
		{
			// image without imageId, not able to cache.
			drawImage( image, imageX, imageY, height, width, helpText );
			return;
		}
		template = contentByte.createTemplate( width, height );
		template.addImage( image, width, 0, 0, height, 0, 0 );
	}
	// Cache the image
	if ( imageId != null && template != null )
	{
		pageDevice.getImageCache( ).put( imageId, template );
	}
	if ( template != null )
	{
		drawImage( template, imageX, imageY, height, width, helpText );
	}
}
 
Example #25
Source File: TextOnlySignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void showText(ITextFontMetrics iTextFontMetrics, Rectangle sigFieldRect) {
	
	SignatureImageTextParameters textParameters = parameters.getTextParameters();
	String text = textParameters.getText();

	float size = getProperSize();
	
	PdfTemplate layer = appearance.getLayer(2);
	layer.setFontAndSize(iTextFont.getBaseFont(), size);
	
	Rectangle boundingRectangle = new Rectangle(sigFieldRect.getWidth(), sigFieldRect.getHeight()); // defines text field borders
	boundingRectangle.setBackgroundColor(parameters.getTextParameters().getBackgroundColor());
	layer.rectangle(boundingRectangle);
	
	layer.setBoundingBox(boundingRectangle);
	layer.setColorStroke(textParameters.getTextColor());
	
	String[] lines = iTextFontMetrics.getLines(text);
	
	layer.beginText();
	
	float strHeight = iTextFontMetrics.getHeight(lines[0], size);
	float y = boundingRectangle.getHeight() - textParameters.getPadding();
	float x = textParameters.getPadding();
	
	layer.moveText(x, y);
	layer.newlineText();

	y = -strHeight;

       float previousOffset = 0;
	for (String line : lines) {
           float offsetX = 0;
		float lineWidth = iTextFontMetrics.getWidth(line, size);
		switch (textParameters.getSignerTextHorizontalAlignment()) {
			case RIGHT:
				offsetX = boundingRectangle.getWidth() - lineWidth - textParameters.getPadding() * 2 - previousOffset;
				break;
			case CENTER:
				offsetX = (boundingRectangle.getWidth() - lineWidth) / 2 - textParameters.getPadding() - previousOffset;
				break;
			default:
				break;
		}
		previousOffset += offsetX;
		layer.moveText(offsetX, y);
		layer.newlineShowText(line);
	}
	
	layer.endText();
}
 
Example #26
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
private void drawImage( PdfTemplate image, float imageX, float imageY,
		float width, float height )
		throws DocumentException
{
	drawImage( image, imageX, imageY, height, width, null );
}
 
Example #27
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) {
            }
        }
    }
}
 
Example #28
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
protected PdfTemplate generateTemplateFromSVG( String svgPath,
		byte[] svgData, float x, float y, float height, float width,
		String helpText ) throws Exception
{
	return transSVG( null, svgData, x, y, height, width, helpText );
}
 
Example #29
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 #30
Source File: ColumnIrregularTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Demonstrates the use of ColumnText.
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();

	// step 2: creation of the writer
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("columnirregular.pdf"));

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

	// step 4:
	// we grab the contentbyte and do some stuff with it
	PdfContentByte cb = writer.getDirectContent();

	PdfTemplate t = cb.createTemplate(600, 800);
	Image caesar = Image.getInstance(PdfTestBase.RESOURCES_DIR + "caesar_coin.jpg");
	cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
	t.setGrayFill(0.75f);
	t.moveTo(310, 112);
	t.lineTo(280, 60);
	t.lineTo(340, 60);
	t.closePath();
	t.moveTo(310, 790);
	t.lineTo(310, 710);
	t.moveTo(310, 580);
	t.lineTo(310, 122);
	t.stroke();
	cb.addTemplate(t, 0, 0);

	ColumnText ct = new ColumnText(cb);
	ct.addText(new Phrase(
			"GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur.  Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt.  Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt.\n",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));
	ct.addText(new Phrase(
			"[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]\n",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));
	ct.addText(new Phrase(
			"Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix.  Is M. Messala, [et P.] M.  Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent:  perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri.  Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur:  una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit.  His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur.  Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.\n",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));
	ct.addText(new Phrase(
			"His rebus adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare.  Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant.  Ad eas res conficiendas Orgetorix deligitur.  Is sibi legationem ad civitates suscipit.  In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat.  Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset:  non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat.  Hac oratione adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant.\n",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));
	ct.addText(new Phrase(
			"Ea res est Helvetiis per indicium enuntiata.  Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur.  Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit.  Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit.",
			FontFactory.getFont(FontFactory.HELVETICA, 12)));

	float[] left1 = { 70, 790, 70, 60 };
	float[] right1 = { 300, 790, 300, 700, 240, 700, 240, 590, 300, 590, 300, 106, 270, 60 };
	float[] left2 = { 320, 790, 320, 700, 380, 700, 380, 590, 320, 590, 320, 106, 350, 60 };
	float[] right2 = { 550, 790, 550, 60 };

	int status = 0;
	int column = 0;
	while ((status & ColumnText.NO_MORE_TEXT) == 0) {
		if (column == 0) {
			ct.setColumns(left1, right1);
			column = 1;
		} else {
			ct.setColumns(left2, right2);
			column = 0;
		}
		status = ct.go();
		ct.setYLine(790);
		ct.setAlignment(Element.ALIGN_JUSTIFIED);
		status = ct.go();
		if ((column == 0) && ((status & ColumnText.NO_MORE_COLUMN) != 0)) {
			document.newPage();
			cb.addTemplate(t, 0, 0);
			cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
		}
	}

	// step 5: we close the document
	document.close();
}