Java Code Examples for com.itextpdf.text.Document#add()

The following examples show how to use com.itextpdf.text.Document#add() . 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: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With
 * a different starting file, though, it doesn't, cf.
 * {@link #testAddUnicodeStampEg_01()}. This test creates a new PDF with the same
 * font and chunk as stamped by the OP. Adobe Reader has no problem with it either.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testCreateUnicodePdf() throws DocumentException, IOException
{
    Document document = new Document();
    try (   OutputStream result  = new FileOutputStream(new File(RESULT_FOLDER, "unicodePdf.pdf")) )
    {
        PdfWriter.getInstance(document, result);
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        document.open();
        
        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        document.add(p);
        
        document.close();
    }
}
 
Example 2
Source File: CreateAndAppendDoc.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-document-using-it">
 * how to create a PDF and you then merge another pdf to the same document using itext
 * </a>
 * <p>
 * Testing the OP's method with <code>paginate</code> set to <code>true</code>
 * </p>
 */
@Test
public void testAppendPDFsPaginate() throws IOException, DocumentException
{
    try (
            InputStream testA4Stream = getClass().getResourceAsStream("testA4.pdf");
            InputStream fromStream = getClass().getResourceAsStream("from.pdf");
            InputStream prefaceStream = getClass().getResourceAsStream("preface.pdf");
            InputStream type3Stream = getClass().getResourceAsStream("Test_Type3_Problem.pdf");
            FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfsPaginate.pdf"));
        )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        document.add(new Paragraph("Some content to start with"));
        appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, document, null, true);
        document.close();
    }
}
 
Example 3
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createSimpleImagePdf() 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();

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

    document.close();

    return baos.toByteArray();
}
 
Example 4
Source File: ChangeMargins.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38057241/itextpdf-different-margin-on-specific-page">
 * itextpdf different margin on specific page
 * </a>
 * <p>
 * This test shows how to set different margins to separate pages.
 * </p> 
 */
@Test
public void testChangingMargins() throws IOException, DocumentException
{
    StringBuilder builder = new StringBuilder("test");
    for (int i = 0; i < 100; i++)
        builder.append(" test");
    String test = builder.toString();
    
    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "ChangingMargins.pdf")))
    {
        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();

        for (int m = 0; m < pdfDocument.getPageSize().getWidth() / 2 && m < pdfDocument.getPageSize().getHeight() / 2; m += 100)
        {
            // pdfDocument.setMargins(m, m, 100, 100);
            pdfDocument.setMargins(m, m, m, m);
            pdfDocument.newPage();
            pdfDocument.add(new Paragraph(test));
        }

        pdfDocument.close();
    }
}
 
Example 5
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 6
Source File: PdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
public void addNewline(Document doc, int i) throws DocumentException {
	if (i > 0) {
		for (int j = 0; j < i; j++) {
			doc.add(Chunk.NEWLINE);
		}
	}
}
 
Example 7
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 8
Source File: ColorParagraphBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testParagraphBackgroundEventListener() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "document-with-paragraph-backgrounds.pdf")));
    ParagraphBackground border = new ParagraphBackground();
    writer.setPageEvent(border);
    document.open();
    document.add(new Paragraph("Hello,"));
    document.add(new Paragraph("In this document, we'll add several paragraphs that will trigger page events. As long as the event isn't activated, nothing special happens, but let's make the event active and see what happens:"));
    border.setActive(true);
    document.add(new Paragraph("This paragraph now has a background. Isn't that fantastic? By changing the event, we can even draw a border, change the line width of the border and many other things. Now let's deactivate the event."));
    border.setActive(false);
    document.add(new Paragraph("This paragraph no longer has a background."));
    document.close();
}
 
Example 9
Source File: LandscapePdf.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/47209312/i-have-a-trouble-with-lowagie-pdf-and-report-making-i-cant-include-headerfooter">
 * I have a trouble with lowagie pdf and Report Making. I cant include headerfooter on the first page
 * </a>
 * <p>
 * This example shows how to generate a PDF with page level
 * settings (page size, page margins) customized already on
 * the first page.
 * </p>
 */
@Test
public void testCreateLandscapeDocument() throws FileNotFoundException, DocumentException {
    Document document = new Document();

    PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "landscape.pdf")));

    document.setPageSize(PageSize.A4.rotate());
    document.setMargins(60, 30, 30, 30);
    document.open();
    document.add(new Paragraph("Test string for a landscape PDF."));
    document.close();
}
 
Example 10
Source File: PDFView.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
protected void buildPdfDocument(        
		Map<String, Object> model,        
		Document document,        
		PdfWriter writer,        
		HttpServletRequest req,        
		HttpServletResponse resp)        
				throws Exception {
	
	
	// Get data "articles" from model
	@SuppressWarnings("unchecked")
	List<HrmsLogin> users = (List<HrmsLogin>) model.get("allUsers");
	
	// Fonts
	Font fontTitle = new Font(FontFamily.TIMES_ROMAN, 14, Font.BOLD, BaseColor.BLACK);
	Font fontTag = new Font(FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.WHITE);

	for(HrmsLogin user: users){

		// 1.Title
		document.add(new Chunk("Employee ID: "));
		Chunk title = new Chunk(user.getHrmsEmployeeDetails().getEmpId()+"", fontTitle);
		document.add(title);
		document.add(new Chunk(" "));

		// -- newline
		document.add(Chunk.NEWLINE);

		// 2.URL
		document.add(new Chunk("Username: "));
		Chunk title2 = new Chunk(user.getUsername(), fontTitle);
		document.add(title2);
		document.add(new Chunk(" "));
		
		// -- newline
		document.add(Chunk.NEWLINE);

		// 3.Categories
		document.add(new Chunk("Password: "));
		Chunk title3 = new Chunk(user.getPassword(), fontTitle);
		document.add(title3);
		document.add(new Chunk(" "));
		
		// -- newline
		document.add(Chunk.NEWLINE);
		
		// 4.Tags
		document.add(new Chunk("Employee ID: "));
		Chunk title4 = new Chunk(user.getRole(), fontTitle);
		document.add(title4);
		document.add(new Chunk(" "));
		
		// -- newline
		document.add(Chunk.NEWLINE);
		document.add(Chunk.NEWLINE);

	}
	

}
 
Example 11
Source File: ImportPageWithoutFreeSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/31980979/itext-importing-styled-text-and-informations-from-an-existing-pdf">
 * iText: Importing styled Text and informations from an existing PDF
 * </a>
 * <p>
 * This method demonstrates how to import merely the region of a PDF page with
 * actual content. The main necessity is to call {@link #cropPdf(PdfReader)}
 * for the reader in question which restricts the media boxes of the pages to
 * the bounding box of the existing content.
 * </p>
 */
@Test
public void testImportPages() throws DocumentException, IOException
{
    byte[] docText = createSimpleTextPdf();
    Files.write(new File(RESULT_FOLDER, "textOnly.pdf").toPath(), docText);
    byte[] docGraphics = createSimpleCircleGraphicsPdf();
    Files.write(new File(RESULT_FOLDER, "graphicsOnly.pdf").toPath(), docGraphics);

    PdfReader readerText = new PdfReader(docText);
    cropPdf(readerText);
    PdfReader readerGraphics = new PdfReader(docGraphics);
    cropPdf(readerGraphics);
    try (   FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "importPages.pdf")))
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        document.open();
        document.add(new Paragraph("Let's import 'textOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));
        document.add(Image.getInstance(writer.getImportedPage(readerText, 1)));
        document.add(new Paragraph("and now 'graphicsOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));
        document.add(Image.getInstance(writer.getImportedPage(readerGraphics, 1)));
        document.add(new Paragraph("That's all, folks!", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));

        document.close();
    }
    finally
    {
        readerText.close();
        readerGraphics.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: StampHeader.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
byte[] createSampleDocument() throws IOException, DocumentException
{
	try (	ByteArrayOutputStream baos = new ByteArrayOutputStream()	)
	{
		Document doc = new Document(new RectangleReadOnly(842,595));
		PdfWriter.getInstance(doc, baos);
		doc.open();
		doc.add(new Paragraph("Test Page 1"));
		doc.newPage();
		doc.add(new Paragraph("Test Page 2"));
		doc.close();
		return baos.toByteArray();
	}
}
 
Example 14
Source File: PDFMigrationReportWriter.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void addTitlePage(Document document)
		throws DocumentException {
	Paragraph preface = new Paragraph();
	// Lets write a big header
	preface.add(new Paragraph(report.getName(), catFont));
	//addEmptyLine(preface, 1);
	// Will create: Report generated by: _name, _date
	preface.add(new Paragraph(new SimpleDateFormat("dd MMM yyyy",new Locale(Platform.getNL())).format(new Date()), smallBold));
	document.add(preface);

}
 
Example 15
Source File: PdfGenerator.java    From book118-downloader with MIT License 5 votes vote down vote up
/**
 * 使用图片创建PDF文件
 *
 * @param srcPahOfImg  图片文件夹路径
 * @param desPathOfPdf PDF存储路径
 * @throws DocumentException pdf相关错误
 * @throws IOException       图片相关错误
 */
public static void creatPDF(String srcPahOfImg, String desPathOfPdf, String sSufix) throws DocumentException, IOException {

    File file = new File(srcPahOfImg);
    File[] picFiles = file.listFiles();
    if (picFiles == null || picFiles.length == 0) {
        return;
    }
    List<File> files = Arrays.asList(picFiles);
    files.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));

    //需要根据第一页创建document的大小
    //如果不根据第一页创建,即使修改document的大小也不会生效,困惑
    // Fix: 创建文档是需要指定文档的尺寸, 该尺寸为文档的默认尺寸
    // Fix: setPageSize 修改的是加入文档的最后一页, 因此需要先添加页,再修改文档大小
    Image firstImg = Image.getInstance(files.get(0).getCanonicalPath());
    Document document = new Document(new Rectangle(firstImg.getWidth(), firstImg.getHeight()), 0, 0, 0, 0);
    PdfWriter.getInstance(document, new FileOutputStream(desPathOfPdf));
    document.open();

    for (File picFile : picFiles) {
        String sFileName = picFile.getCanonicalPath();
        // 过滤出指定后缀名的文件
        if (!sFileName.substring(sFileName.lastIndexOf('.') + 1).equals(sSufix)) { continue; }
        Image img = Image.getInstance(sFileName);
        document.add(img);
        document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
    }
    document.close();
}
 
Example 16
Source File: PdfExportTest.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private void getChapter2(Document document) throws DocumentException {

        NormalTitle title = new NormalTitle("JSON测试", 2);
        NormalSubTitle title1 = new NormalSubTitle(title, "对象数组", 1);
        NormalSubTitle title2 = new NormalSubTitle(title1, "基本信息", 1, 10);
        title2.getFont().setSize(12F);
        NormalContent content = new NormalContent();
        Map<String, String> data = new LinkedHashMap<String, String>();
        data.put("请求类型", "HTTP");
        data.put("接口地址", "http://www.xiaoyaoji.com.cn/test/json/3.json");
        data.put("请求方式", "GET");
        data.put("数据类型", "X-WWW-FORM-URLENCODED");
        data.put("响应类型", "JSON");
        data.put("接口状态", "启用");
        content.addContent(data);
        title2.add(content);
        NormalSubTitle title3 = new NormalSubTitle(title1, "响应数据", 2, 10);
        title3.getFont().setSize(12F);
        NormalContent content3 = new NormalContent();
        List<List<Object>> table = new ArrayList<List<Object>>();
        Object[] header = new Object[]{"参数名称", "是否必须", "数据类型", "描述"};
        Object[] param1 = new Object[]{"menu", "true", "object", ""};
        Object[] param2 = new Object[]{"menu.header", "true", "string", ""};
        Object[] param3 = new Object[]{"items.header", "true", "array[object]", ""};
        Object[] param4 = new Object[]{"items.id", "true", "string", ""};
        Object[] param5 = new Object[]{"items.label", "true", "string", ""};
        table.add(Arrays.asList(header));
        table.add(Arrays.asList(param1));
        table.add(Arrays.asList(param2));
        table.add(Arrays.asList(param3));
        table.add(Arrays.asList(param4));
        table.add(Arrays.asList(param5));
        content3.addTable(table);
        title3.add(content3);
        document.add(title);
    }
 
Example 17
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private String createPdf(Context context) throws Exception {
	BscReportPropertyUtils.loadData();
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}		
	FontFactory.register(BscConstants.PDF_ITEXT_FONT);
	String fileName = SimpleUtils.getUUIDStr() + ".pdf";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
	OutputStream os = new FileOutputStream(fileFullPath);
	Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);	
	document.left(100f);
	document.top(150f);
	PdfWriter writer = PdfWriter.getInstance(document, os);
	document.open();  
	
	PdfPTable table = new PdfPTable(MAX_COLSPAN);
	table.setWidthPercentage(100f);	
	PdfPTable signTable = new PdfPTable( 1 );
	signTable.setWidthPercentage(100f);		
	
	this.createHead(table, vision, context);
	this.createBody(table, vision);
	
	this.putSignature(signTable, context);		
	
	document.add(table); 
	document.add(signTable);
	document.close();
	writer.close();			
	
	os.flush();
	os.close();
	os = null;
	
	File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "department-report.pdf");
	file = null;
	return oid;		
}
 
Example 18
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private String createPdf(Context context) throws Exception {
	BscReportPropertyUtils.loadData();
	BscReportSupportUtils.loadExpression(); // 2015-04-18 add
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}		
	FontFactory.register(BscConstants.PDF_ITEXT_FONT);
	String fileName = SimpleUtils.getUUIDStr() + ".pdf";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
	OutputStream os = new FileOutputStream(fileFullPath);
	//Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
	Document document = new Document(PageSize.A4, 10, 10, 10, 10);		
	document.left(100f);
	document.top(150f);
	PdfWriter writer = PdfWriter.getInstance(document, os);
	document.open();  
	
	int dateRangeRows = 4 + vision.getPerspectives().get(0).getObjectives().get(0).getKpis().get(0).getDateRangeScores().size();
	PdfPTable table = new PdfPTable(MAX_COLSPAN);
	PdfPTable dateRangeTable = new PdfPTable( dateRangeRows );
	PdfPTable chartsTable = new PdfPTable( 2 );
	PdfPTable signTable = new PdfPTable( 1 );
	table.setWidthPercentage(100f);	
	dateRangeTable.setWidthPercentage(100f);
	chartsTable.setWidthPercentage(100f);
	signTable.setWidthPercentage(100f);
	
	this.createHead(table, vision);
	this.createBody(table, vision);
	this.createDateRange(dateRangeTable, vision, context, dateRangeRows);		
	this.putCharts(chartsTable, context);
	this.putSignature(signTable, context);
	
	document.add(chartsTable);
	document.add(table);  
	document.add(dateRangeTable);  
	document.add(signTable);
	document.close();
	writer.close();			
	
	os.flush();
	os.close();
	os = null;
	
	File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "kpi-report.pdf");
	file = null;
	return oid;
}
 
Example 19
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());
    }
}
 
Example 20
Source File: PageBreaks.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42412002/xmlworker-itext-doesnt-break-page-in-pdf-result">
 * XMLWorker (iText) doesn't break page in PDF result
 * </a>
 * <br/>
 * <a href="http://developers.itextpdf.com/fr/node/2078#999-parsehtml7.java">
 * ParseHtml7 iText example
 * </a>
 * <p>
 * Indeed, the ParseHtml7 iText example does not respect page-break-before
 * style entries. The cause is that they are only supported when the elements
 * generated by the XML worker are directly added to the Document, not when
 * they are added to a table cell as in your example. Unfortunately RTL is
 * only supported inside table cells.
 * </p>
 * <p>
 * {@link #testParseHtml7Improved()} shows how to explicitly support the
 * page-break-before style entries by recognizing the {@link Chunk#NEWPAGE}
 * elements generated for page-break-before elements and creating a new page
 * then. 
 * </p>
 */
@Test
public void testParseHtml7Original() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("PageBreaks.html")    )
    {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "PageBreaks.pdf")));
        // step 3
        document.open();
        // step 4
        // Styles
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontProvider.register("src/test/resources/mkl/testarea/itext5/xmlworker/NotoNaskhArabic-Regular.ttf");
        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        // Pipelines
        ElementList elements = new ElementList();
        ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
 
        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);
        p.parse(resource, Charset.forName("UTF-8"));
 
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell = new PdfPCell();
        cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
        for (Element e : elements) {
            cell.addElement(e);
        }
        table.addCell(cell);
        document.add(table);
        // step 5
        document.close();
    }
}