Java Code Examples for com.itextpdf.text.Image#getInstance()

The following examples show how to use com.itextpdf.text.Image#getInstance() . 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: PDFSampleMain.java    From tutorials with MIT License 7 votes vote down vote up
private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException {
    Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
    Image img = Image.getInstance(path.toAbsolutePath().toString());
    img.scalePercent(10);

    PdfPCell imageCell = new PdfPCell(img);
    table.addCell(imageCell);

    PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
    horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(horizontalAlignCell);

    PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
    verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    table.addCell(verticalAlignCell);
}
 
Example 2
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example 3
Source File: PersonalReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example 4
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createMultiUseImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();

    BufferedImage bim = new BufferedImage(500, 250, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 250, 250);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    document.add(image);
    document.add(image);
    document.add(image);

    document.close();

    return baos.toByteArray();
}
 
Example 5
Source File: PDFExport.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
private PdfPCell getCells(MagicCard card) throws BadElementException, IOException {

		Image image1 = null;
		try {
			image1 = Image.getInstance(MTGControler.getInstance().getEnabled(MTGPictureProvider.class).getPicture(card, null),
					null);
		} catch (Exception e) {
			image1 = Image.getInstance(MTGControler.getInstance().getEnabled(MTGPictureProvider.class).getBackPicture(), null);
		}

		int h = getInt("CARD_HEIGHT");
		int w = getInt("CARD_WIDTH");

		image1.scaleAbsolute(w, h);

		PdfPCell cell = new PdfPCell(image1, false);
		cell.setBorder(0);
		cell.setPadding(5);
	
		return cell;
	}
 
Example 6
Source File: TestTrimPdfPage.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testWithWriter() throws DocumentException, IOException
{
    InputStream resourceStream = getClass().getResourceAsStream("test.pdf");
    try
    {
        PdfReader reader = new PdfReader(resourceStream);
        Rectangle pageSize = reader.getPageSize(1);

        Rectangle rect = getOutputPageSize(pageSize, reader, 1);

        Document document = new Document(rect, 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-writer.pdf")));

        document.open();
        PdfImportedPage page;

        // Go through all pages
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++)
        {
            document.newPage();
            page = writer.getImportedPage(reader, i);
            System.out.println("BBox:  "+ page.getBoundingBox().toString());
            Image instance = Image.getInstance(page);
            document.add(instance);
            Rectangle outputPageSize = document.getPageSize();
            System.out.println(outputPageSize.toString());
        }
        document.close();
    }
    finally
    {
        if (resourceStream != null)
            resourceStream.close();
    }
}
 
Example 7
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example 8
Source File: PdfCleanUpContentOperator.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
private void updateImageStream(PRStream imageStream, byte[] newData) throws BadElementException, IOException, BadPdfFormatException {
    PdfImage image = new PdfImage(Image.getInstance(newData), "", null);

    if (imageStream.contains(PdfName.SMASK)) {
        image.put(PdfName.SMASK, imageStream.get(PdfName.SMASK));
    }

    if (imageStream.contains(PdfName.MASK)) {
        image.put(PdfName.MASK, imageStream.get(PdfName.MASK));
    }

    if (imageStream.contains(PdfName.SMASKINDATA)) {
        image.put(PdfName.SMASKINDATA, imageStream.get(PdfName.SMASKINDATA));
    }

    imageStream.clear();
    imageStream.putAll(image);
    imageStream.setDataRaw(image.getBytes());
}
 
Example 9
Source File: PDFMigrationReportWriter.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private com.itextpdf.text.Image getImageForStatus(int status) throws BadElementException, MalformedURLException, IOException {
	switch (status) {
	case IStatus.OK: Image im =  Image.getInstance(FileLocator.toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/valid.png")));im.setCompressionLevel(12);im.scaleToFit(12, 12);return im;
	case IStatus.WARNING:  im = Image.getInstance(FileLocator.toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/warning.gif")));im.setCompressionLevel(12);im.scaleToFit(16, 16);return im;
	case IStatus.ERROR:  im = Image.getInstance(FileLocator.toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/error.png")));im.setCompressionLevel(12);im.scaleToFit(12, 12);return im;
	default:break;
	}

	return null;
}
 
Example 10
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createClippingTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();
    directContent.beginText();
    directContent.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_CLIP);
    directContent.setTextMatrix(AffineTransform.getTranslateInstance(100, 400));
    directContent.setFontAndSize(BaseFont.createFont(), 100);
    directContent.showText("Test");
    directContent.endText();
    
    BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    directContent.addImage(image, 500, 0, 0, 599, 50, 50);
    document.close();

    return baos.toByteArray();
}
 
Example 11
Source File: JFreeChartTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName)
{
    PdfWriter writer = null;
    Document document = new Document();

    try
    {
        writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        PdfContentByte pdfContentByte = writer.getDirectContent();
        PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(50, 50);
        Graphics2D graphics2d = new PdfGraphics2D(pdfTemplateChartHolder, 50, 50);
        Rectangle2D chartRegion = new Rectangle2D.Double(0, 0, 50, 50);
        chart.draw(graphics2d, chartRegion);
        graphics2d.dispose();

        Image chartImage = Image.getInstance(pdfTemplateChartHolder);
        document.add(chartImage);

        PdfPTable table = new PdfPTable(5);
        // the cell object
        // we add a cell with colspan 3

        PdfPCell cellX = new PdfPCell(new Phrase("A"));
        cellX.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
        cellX.setRowspan(6);
        table.addCell(cellX);

        PdfPCell cellA = new PdfPCell(new Phrase("A"));
        cellA.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
        cellA.setColspan(4);
        table.addCell(cellA);

        PdfPCell cellB = new PdfPCell(new Phrase("B"));
        table.addCell(cellB);
        PdfPCell cellC = new PdfPCell(new Phrase("C"));
        table.addCell(cellC);
        PdfPCell cellD = new PdfPCell(new Phrase("D"));
        table.addCell(cellD);
        PdfPCell cellE = new PdfPCell(new Phrase("E"));
        table.addCell(cellE);
        PdfPCell cellF = new PdfPCell(new Phrase("F"));
        table.addCell(cellF);
        PdfPCell cellG = new PdfPCell(new Phrase("G"));
        table.addCell(cellG);
        PdfPCell cellH = new PdfPCell(new Phrase("H"));
        table.addCell(cellH);
        PdfPCell cellI = new PdfPCell(new Phrase("I"));
        table.addCell(cellI);

        PdfPCell cellJ = new PdfPCell(new Phrase("J"));
        cellJ.setColspan(2);
        cellJ.setRowspan(3);
        //instead of
        //  cellJ.setImage(chartImage);
        //the OP now uses
        Chunk chunk = new Chunk(chartImage, 20, -50);
        cellJ.addElement(chunk);
        //presumably with different contents of the other cells at hand
        table.addCell(cellJ);

        PdfPCell cellK = new PdfPCell(new Phrase("K"));
        cellK.setColspan(2);
        table.addCell(cellK);
        PdfPCell cellL = new PdfPCell(new Phrase("L"));
        cellL.setColspan(2);
        table.addCell(cellL);
        PdfPCell cellM = new PdfPCell(new Phrase("M"));
        cellM.setColspan(2);
        table.addCell(cellM);

        document.add(table);

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    document.close();
}
 
Example 12
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createSmaskImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();

    BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    BufferedImage bmask = new BufferedImage(500, 500, BufferedImage.TYPE_BYTE_GRAY);
    g2d = bmask.createGraphics();
    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.setColor(Color.BLACK);
    g2d.fillRect(200, 0, 100, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    Image mask = Image.getInstance(bmask, null, true);
    mask.makeMask();
    image.setImageMask(mask);
    document.add(image);

    document.close();

    return baos.toByteArray();
}
 
Example 13
Source File: StampInLayer.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/31507132/itextsharp-form-gets-flattened-even-when-the-formflattening-property-is-false">
 * Itextsharp form gets flattened even when the FormFlattening property is false
 * </a>
 * <p>
 * Reproducing the issue without work-around.
 * </p>
 */
@Test
public void testStampInLayerOnLayeredBug() throws IOException, DocumentException
{
    try (   InputStream source = getClass().getResourceAsStream("House_Plan_Final.pdf");
            InputStream image = getClass().getResourceAsStream("Willi-1.jpg"))
    {
        Image iImage = Image.getInstance(StreamUtil.inputStreamToArray(image));
        byte[] result = stampLayer(source, iImage, 100, 100, "Logos", false);
        Files.write(new File(RESULT_FOLDER, "House_Plan_Final-stamped-bug.pdf").toPath(), result);
    }
}
 
Example 14
Source File: StampInLayer.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/31507132/itextsharp-form-gets-flattened-even-when-the-formflattening-property-is-false">
 * Itextsharp form gets flattened even when the FormFlattening property is false
 * </a>
 * <p>
 * Reproducing the issue with work-around.
 * </p>
 */
@Test
public void testStampInLayerOnLayeredWorkAround() throws IOException, DocumentException
{
    try (   InputStream source = getClass().getResourceAsStream("House_Plan_Final.pdf");
            InputStream image = getClass().getResourceAsStream("Willi-1.jpg"))
    {
        Image iImage = Image.getInstance(StreamUtil.inputStreamToArray(image));
        byte[] result = stampLayer(source, iImage, 100, 100, "Logos", true);
        Files.write(new File(RESULT_FOLDER, "House_Plan_Final-stamped-workAround.pdf").toPath(), result);
    }
}
 
Example 15
Source File: PdfReportPageNumber.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a header to every page
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
 *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
	PdfPTable table = new PdfPTable(3);
	try {
		table.setWidths(new int[]{40,5,10});
		table.setTotalWidth(100);
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
		Font font=new Font(chineseFont,8);
		font.setColor(new BaseColor(55,55,55));
		Paragraph paragraph=new Paragraph("第   "+writer.getPageNumber()+" 页   共",font);
		paragraph.setAlignment(Element.ALIGN_RIGHT);
		table.addCell(paragraph);
		Image img=Image.getInstance(total);
		img.scaleAbsolute(28, 28);
		PdfPCell cell = new PdfPCell(img);
		cell.setBorder(Rectangle.NO_BORDER);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);
		PdfPCell c = new PdfPCell(new Paragraph("页",font));
		c.setHorizontalAlignment(Element.ALIGN_LEFT);
		c.setBorder(Rectangle.NO_BORDER);
		table.addCell(c);
		float center=(document.getPageSize().getWidth())/2-120/2;
		table.writeSelectedRows(0, -1,center,30, writer.getDirectContent());
	}
	catch(DocumentException de) {
		throw new ExceptionConverter(de);
	}
}
 
Example 16
Source File: PdfCleanUpRenderListener.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
public void renderImage(ImageRenderInfo renderInfo) {
    List<Rectangle> areasToBeCleaned = getImageAreasToBeCleaned(renderInfo);

    if (areasToBeCleaned == null) {
        chunks.add(new PdfCleanUpContentChunk.Image(false, null));
    } else {
        try {
            PdfImageObject pdfImage = renderInfo.getImage();
            byte[] imageBytes = processImage(pdfImage.getImageAsBytes(), areasToBeCleaned);

            if (renderInfo.getRef() == null && pdfImage != null) { // true => inline image
                PdfDictionary dict = pdfImage.getDictionary();
                PdfObject imageMask = dict.get(PdfName.IMAGEMASK);
                Image image = Image.getInstance(imageBytes);

                if (imageMask == null) {
                    imageMask = dict.get(PdfName.IM);
                }

                if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE)) {
                    image.makeMask();
                }

                PdfContentByte canvas = getContext().getCanvas();
                canvas.addImage(image, 1, 0, 0, 1, 0, 0, true);
            } else if (pdfImage != null && imageBytes != pdfImage.getImageAsBytes()) {
                chunks.add(new PdfCleanUpContentChunk.Image(true, imageBytes));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 17
Source File: AddRotatedImage.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39364197/how-to-rotate-around-the-image-center-by-itext">
 * How to rotate around the image center by itext?
 * </a>
 * <p>
 * This test draws an image at given coordinates without rotation and then again
 * as if that image was rotated around its center by some angle.
 * </p>
 */
@Test
public void testAddRotatedImage() throws IOException, DocumentException
{
    try (   FileOutputStream stream = new FileOutputStream(new File(RESULT_FOLDER, "rotatedImage.pdf"))    )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, stream);
        document.open();

        PdfContentByte contentByte = writer.getDirectContent();

        int x = 200;
        int y = 300;
        float rotate = (float) Math.PI / 3;

        try (InputStream imageStream = getClass().getResourceAsStream("/mkl/testarea/itext5/layer/Willi-1.jpg"))
        {
            Image image = Image.getInstance(IOUtils.toByteArray(imageStream));

            // Draw image at x,y without rotation
            contentByte.addImage(image, image.getWidth(), 0, 0, image.getHeight(), x, y);

            // Draw image as if the previous image was rotated around its center
            // Image starts out being 1x1 with origin in lower left
            // Move origin to center of image
            AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5);
            // Stretch it to its dimensions
            AffineTransform B = AffineTransform.getScaleInstance(image.getWidth(), image.getHeight());
            // Rotate it
            AffineTransform C = AffineTransform.getRotateInstance(rotate);
            // Move it to have the same center as above
            AffineTransform D = AffineTransform.getTranslateInstance(x + image.getWidth()/2, y + image.getHeight()/2);
            // Concatenate
            AffineTransform M = (AffineTransform) A.clone();
            M.preConcatenate(B);
            M.preConcatenate(C);
            M.preConcatenate(D);
            //Draw
            contentByte.addImage(image, M);
        }

        document.close();
    }
}
 
Example 18
Source File: AddRotatedImage.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39364197/how-to-rotate-around-the-image-center-by-itext">
 * How to rotate around the image center by itext?
 * </a>
 * <p>
 * This test draws an image at given coordinates without rotation and then again
 * as if that image was flipped and rotated around its center by some angle.
 * </p>
 */
@Test
public void testAddRotatedFlippedImage() throws IOException, DocumentException
{
    try (   FileOutputStream stream = new FileOutputStream(new File(RESULT_FOLDER, "rotatedFlippedImage.pdf"))    )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, stream);
        document.open();

        PdfContentByte contentByte = writer.getDirectContent();

        int x = 200;
        int y = 300;
        float rotate = (float) Math.PI / 3;

        try (InputStream imageStream = getClass().getResourceAsStream("/mkl/testarea/itext5/layer/Willi-1.jpg"))
        {
            Image image = Image.getInstance(IOUtils.toByteArray(imageStream));

            // Draw image at x,y without rotation
            contentByte.addImage(image, image.getWidth(), 0, 0, image.getHeight(), x, y);

            // Draw image as if the previous image was flipped and rotated around its center
            // Image starts out being 1x1 with origin in lower left
            // Move origin to center of image
            AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5);
            // Flip it horizontally
            AffineTransform B = new AffineTransform(-1, 0, 0, 1, 0, 0);
            // Stretch it to its dimensions
            AffineTransform C = AffineTransform.getScaleInstance(image.getWidth(), image.getHeight());
            // Rotate it
            AffineTransform D = AffineTransform.getRotateInstance(rotate);
            // Move it to have the same center as above
            AffineTransform E = AffineTransform.getTranslateInstance(x + image.getWidth()/2, y + image.getHeight()/2);
            // Concatenate
            AffineTransform M = (AffineTransform) A.clone();
            M.preConcatenate(B);
            M.preConcatenate(C);
            M.preConcatenate(D);
            M.preConcatenate(E);
            //Draw
            contentByte.addImage(image, M);
        }

        document.close();
    }
}
 
Example 19
Source File: PptxToPDFConverter.java    From docs-to-pdf-converter with MIT License 4 votes vote down vote up
@Override
public void convert() throws Exception {
	loading();
	


	Dimension pgsize = processSlides();
	
	processing();
	
    double zoom = 2; // magnify it by 2 as typical slides are low res
    AffineTransform at = new AffineTransform();
    at.setToScale(zoom, zoom);

	
	Document document = new Document();

	PdfWriter writer = PdfWriter.getInstance(document, outStream);
	document.open();
	
	for (int i = 0; i < getNumSlides(); i++) {

		BufferedImage bufImg = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = bufImg.createGraphics();
		graphics.setTransform(at);
		//clear the drawing area
		graphics.setPaint(getSlideBGColor(i));
		graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
		try{
			drawOntoThisGraphic(i, graphics);
		} catch(Exception e){
			//Just ignore, draw what I have
		}
		
		Image image = Image.getInstance(bufImg, null);
		document.setPageSize(new Rectangle(image.getScaledWidth(), image.getScaledHeight()));
		document.newPage();
		image.setAbsolutePosition(0, 0);
		document.add(image);
	}
	//Seems like I must close document if not output stream is not complete
	document.close();
	
	//Not sure what repercussions are there for closing a writer but just do it.
	writer.close();
	finished();
	

}
 
Example 20
Source File: eReceipt.java    From smartcoins-wallet with MIT License 4 votes vote down vote up
private void generatePdf() {
    try {
        showProgressBar();
        verifyStoragePermissions(this);
        final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getResources().getString(R.string.folder_name) + File.separator + "eReceipt-" + transactionId + ".pdf";
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(path));
        document.open();
        Bitmap bitmap = Bitmap.createBitmap(
                llall.getWidth(),
                llall.getHeight(),
                Bitmap.Config.ARGB_8888);


        Canvas c = new Canvas(bitmap);
        llall.draw(c);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] imageInByte = stream.toByteArray();
        Image myImage = Image.getInstance(imageInByte);
        float documentWidth = document.getPageSize().getWidth();
        float documentHeight = document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin();
        myImage.scaleToFit(documentWidth, documentHeight);
        myImage.setAlignment(Image.ALIGN_CENTER | Image.MIDDLE);
        document.add(myImage);
        document.close();
        this.runOnUiThread(new Runnable() {
            public void run() {
                Intent email = new Intent(Intent.ACTION_SEND);
                Uri uri = Uri.fromFile(new File(path));
                email.putExtra(Intent.EXTRA_STREAM, uri);
                email.putExtra(Intent.EXTRA_SUBJECT, "eReceipt " + date);
                email.setType("application/pdf");
                email.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(email);
            }
        });
        hideProgressBar();
    } catch (Exception e) {
        Log.e(TAG, "Exception while tryig to share receipt info. Msg: " + e.getMessage());
    }
}