Java Code Examples for com.itextpdf.text.pdf.PdfWriter#close()

The following examples show how to use com.itextpdf.text.pdf.PdfWriter#close() . 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: PDFExport.java    From MtgDesktopCompanion with GNU General Public License v3.0 8 votes vote down vote up
@Override
public void exportDeck(MagicDeck deck, File f) throws IOException {
	PdfPTable table = new PdfPTable(3);
	table.setHorizontalAlignment(Element.ALIGN_CENTER);

	try {
		document = new Document(PageSize.A4, 5, 5, 10, 5);
		document.addAuthor(getString("AUTHOR"));
		document.addCreationDate();
		document.addCreator(MTGConstants.MTG_APP_NAME);
		document.addTitle(deck.getName());

		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
		document.open();
		document.add(new Chunk(""));
		for (MagicCard card : deck.getMainAsList()) {
			table.addCell(getCells(card));
			notify(card);
		}
		document.add(table);
		document.close();
		writer.close();
	} catch (Exception e) {
		logger.error("Error in pdf creation " + f, e);
	}
}
 
Example 2
Source File: SwingExportUtil.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes swing to pdf
 * 
 * @param panel
 * @param fileName
 * @throws DocumentException
 * @throws Exception
 */
public static void writeToPDF(JComponent panel, File fileName)
    throws IOException, DocumentException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getHeight();
  logger.info(
      () -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));
  Document document = new Document(new Rectangle(width, height));
  PdfWriter writer = null;
  try {
    writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(width, height);
    Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper());
    panel.print(g2);
    g2.dispose();
    contentByte.addTemplate(template, 0, 0);
    document.close();
    writer.close();
  } finally {
    if (document.isOpen()) {
      document.close();
    }
  }
}
 
Example 3
Source File: HtmlExporterUtils.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
/**
 * 将图片转换为 PDF.
 *
 * @param image
 * @param pageSize     supported type will be found in com.itextpdf.text.PageSize,
 *                     like A2, A3, A4, LETTER_LANDSCAPE etc.
 * @param marginLeft   0f
 * @param marginRight  0f
 * @param marginTop    0f
 * @param marginBottom 0f
 * @return PDF 格式的 byte[]
 */
public static byte[] image2pdf(byte[] image, Rectangle pageSize, Float marginLeft, Float marginRight,
                               Float marginTop, Float marginBottom) {

    Document document = new Document(pageSize == null ? PageSize.A4 : pageSize,
            marginLeft == null ? 0f : marginLeft, marginRight == null ? 0f : marginRight,
            marginTop == null ? 0f : marginTop, marginBottom == null ? 0f : marginBottom);
    PdfWriter pdfWriter;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        pdfWriter = PdfWriter.getInstance(document, baos);
        document.open();
        document.add(Image.getInstance(image, true));
        // need close document and pdfWriter before convert byte array!
        document.close();
        pdfWriter.close();
        return baos.toByteArray();
    } catch (DocumentException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: SwingExportUtil.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes swing to pdf
 * 
 * @param panel
 * @param fileName
 * @throws DocumentException
 * @throws Exception
 */
public static void writeToPDF(JComponent panel, File fileName)
    throws IOException, DocumentException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getHeight();
  logger.info(
      () -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));
  Document document = new Document(new Rectangle(width, height));
  PdfWriter writer = null;
  try {
    writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(width, height);
    Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper());
    panel.print(g2);
    g2.dispose();
    contentByte.addTemplate(template, 0, 0);
    document.close();
    writer.close();
  } finally {
    if (document.isOpen()) {
      document.close();
    }
  }
}
 
Example 5
Source File: PDF2ImageExample.java    From tutorials with MIT License 5 votes vote down vote up
private static void generatePDFFromImage(String filename, String extension)
		throws IOException, BadElementException, DocumentException {
	Document document = new Document();
	String input = filename + "." + extension;
	String output = "src/output/" + extension + ".pdf";
	FileOutputStream fos = new FileOutputStream(output);
	PdfWriter writer = PdfWriter.getInstance(document, fos);
	writer.open();
	document.open();
	document.add(Image.getInstance((new URL(input))));
	document.close();
	writer.close();
}
 
Example 6
Source File: PersonalReportPdfCommand.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.createFoot(table, context);
	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, "personal-report.pdf");
	file = null;
	return oid;
}
 
Example 7
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 8
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 9
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 4 votes vote down vote up
public void GeneratePDF()
{
    Document document = new Document();
    try
    {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/sdcard/TutorialesHackro/hoja.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(3); // 3 columns.
        table.setWidthPercentage(100); //Width 100%
        table.setSpacingBefore(10f); //Space before table
        table.setSpacingAfter(10f); //Space after table

        //Set Column widths
        float[] columnWidths = {1f, 1f, 1f};
        table.setWidths(columnWidths);

        PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
        cell1.setBorderColor(BaseColor.BLUE);
        cell1.setPaddingLeft(10);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
        cell2.setBorderColor(BaseColor.GREEN);
        cell2.setPaddingLeft(10);
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
        cell3.setBorderColor(BaseColor.RED);
        cell3.setPaddingLeft(10);
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

        //To avoid having the cell border and the content overlap, if you are having thick cell borders
        //cell1.setUserBorderPadding(true);
        //cell2.setUserBorderPadding(true);
        //cell3.setUserBorderPadding(true);

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);

        document.add(table);

        createDirectoryAndSaveFile(writer, "david");
        document.close();
        writer.close();
    } catch (Exception e)
    {
        e.printStackTrace();
        Log.e("ewdfhyfafedyatfawytedfytew b",e.getMessage());
    }

}
 
Example 10
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();
	

}