Java Code Examples for com.itextpdf.text.Document

The following are top voted examples for showing how to use com.itextpdf.text.Document. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: IMSQTI2PDF   File: PDFCreator.java   View source code 7 votes vote down vote up
public void createPDF(String outputFile, ArrayList<Question> qlist, boolean showCorrectAnswer,
        PageCounter pagecounter, int maximumPageNumber, String inputFolder) throws DocumentException, IOException
{
    _inputFolder = inputFolder;
    Document document = new Document(PageSize.A4, 50, 50, 70, 50);
    PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile));

    pdfwriter.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    pdfwriter.setPageEvent(new HeaderFooter(maximumPageNumber));

    if (pagecounter != null)
    {
        pdfwriter.setPageEvent(pagecounter);
    }

    document.open();

    Paragraph p = new Paragraph();
    // p.setSpacingBefore(SPACING);
    p.setSpacingAfter(SPACING);
    p.setIndentationLeft(INDENTATION);

    writeQuestions(p, document, showCorrectAnswer, qlist);

    document.close();

}
 
Example 2
Project: JYLAND   File: AbstractITextPdfView.java   View source code 7 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
		HttpServletRequest request, HttpServletResponse response) throws Exception {
	// IE workaround: write into byte array first.
	ByteArrayOutputStream baos = createTemporaryOutputStream();

	// Apply preferences and build metadata.
	Document document = newDocument();
	PdfWriter writer = newWriter(document, baos);
	prepareWriter(model, writer, request);
	buildPdfMetadata(model, document, request);

	// Build PDF document.
	document.open();
	buildPdfDocument(model, document, writer, request, response);
	document.close();

	// Flush to HTTP response.
	writeToResponse(response, baos);
}
 
Example 3
Project: CPI   File: generarPDF.java   View source code 7 votes vote down vote up
private static void addMetaData(Document document) {
  document.addTitle("My first PDF");
  document.addSubject("Using iText");
  document.addKeywords("Java, PDF, iText");
  document.addAuthor("Lars Vogel");
  document.addCreator("Lars Vogel");
}
 
Example 4
Project: CPI   File: generarPDF.java   View source code 7 votes vote down vote up
private static void addTitlePage(Document document,Resolucion res)
    throws DocumentException {
  Paragraph preface = new Paragraph();
  // We add one empty line
  addEmptyLine(preface, 1);
  // Lets write a big header
  preface.add(new Paragraph("Consejo Profesional de Informatica de Santiago del Estero", catFont));

  addEmptyLine(preface, 1);
  // Will create: Report generated by: _name, _date
  preface.add(new Paragraph( "Comision Directiva del Consejo, " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      smallBold));
  addEmptyLine(preface, 2);
  preface.add(new Paragraph("Resolucion N°"+res.getNumero_resolucion()+"",
      smallBold));

  addEmptyLine(preface, 3);

  preface.add(new Paragraph("Esta Resolucion de tipo "+res.getTipo()+" formulada para notificar al socio con legajo: "+res.getLegajo_socio()+" de su actual estado como socio del Consejo.\n"
          + res.getDescripcion_solicitud()+" "+res.getDescripcion_resolucion()+" en la fecha "+res.getFecha(),
      cuerpo));

  document.add(preface);
  // Start a new page
  document.newPage();
}
 
Example 5
Project: polyGembler   File: JfreeChart.java   View source code 7 votes vote down vote up
public void print(String plot_pdf) {
	try {
		float width = jframe.getSize().width,
				height = jframe.getSize().height;
		Document document = new Document(new Rectangle(width, height));
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(plot_pdf));
		document.open();
		PdfContentByte canvas = writer.getDirectContent();
		PdfTemplate template = canvas.createTemplate(width, height);
		Graphics2D g2d = new PdfGraphics2D(template, width, height);
		jframe.paint(g2d);
		g2d.dispose();
		canvas.addTemplate(template, 0, 0);
		document.close();
	} catch (FileNotFoundException | DocumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 6
Project: ExcelToBarcode   File: MainController.java   View source code 7 votes vote down vote up
/** Shows a blank document, in case of a problem in generating the PDF */
private byte[] showBlank() throws DocumentException {
    final Document document = new Document(PageSize.LETTER); // FIXME - get PageSize from label definition
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
    final PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    document.add(new Paragraph("No data have been uploaded.  The time is: " + new Date()));
    
    final Barcode128 code128 = new Barcode128();
    code128.setGenerateChecksum(true);
    code128.setCode(new Date().toString());
    
    document.add(code128.createImageWithBarcode(writer.getDirectContent(), null, null));
    document.close();
    return baos.toByteArray();
}
 
Example 7
Project: testarea-itext5   File: EnlargePagePart.java   View source code 7 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35374110/how-do-i-use-itext-to-have-a-landscaped-pdf-on-half-of-a-a4-back-to-portrait-and">
 * How do i use iText to have a landscaped PDF on half of a A4 back to portrait and full size on A4
 * </a>
 * <p>
 * This sample shows how to rotate and enlarge the upper half of an A4 page to fit into a new A4 page.
 * </p>
 */
@Test
public void testRotateAndZoomUpperHalfPage() throws IOException, DocumentException
{
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test-upperHalf.pdf"))   )
    {
        PdfReader reader = new PdfReader(resource);
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, result);
        document.open();

        double sqrt2 = Math.sqrt(2);
        Rectangle pageSize = reader.getPageSize(1);
        PdfImportedPage importedPage = writer.getImportedPage(reader, 1);
        writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2);
        
        document.close();
    }
}
 
Example 8
Project: wasexport   File: PdfExport.java   View source code 6 votes vote down vote up
/**
 * 
 */
@Override
public void exportInnertion(OutputStream servletOut, List header, List data)
		throws IOException {
	// step 1
	Document document = new Document();
	// step 2
	PdfWriter writer;
	try {
		writer = PdfWriter.getInstance(document, servletOut);
	} catch (DocumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return;
	}
	// step 3
	document.open();
	// step 4
	XMLWorkerHelper.getInstance().parseXHtml(writer, document,
			new java.io.StringReader(
			HtmlExport.createHTML(header, data)));
	// step 5
	document.close();

}
 
Example 9
Project: TeamNote   File: ExportUtilImpl.java   View source code 6 votes vote down vote up
public void htmlToPdf(String htmlPath, File pdfFile) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
    document.open();
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(htmlPath), Charset.forName("UTF-8"));
    document.close();
}
 
Example 10
Project: ureport   File: PageHeaderFooterEvent.java   View source code 6 votes vote down vote up
@Override
public void onEndPage(PdfWriter writer, Document document) {
	List<Page> pages=report.getPages();
	int pageNumber=writer.getPageNumber();
	if(pageNumber>pages.size()){
		return;
	}
	Page page=pages.get(pageNumber-1);
	HeaderFooter header=page.getHeader();
	HeaderFooter footer=page.getFooter();
	if(header!=null){
		buildTable(writer,header,true,report);			
	}
	if(footer!=null){
		buildTable(writer,footer,false,report);						
	}
}
 
Example 11
Project: DWSurvey   File: Demo5URL2PDF.java   View source code 6 votes vote down vote up
/**
 * 根据URL提前blog的基本信息,返回结果>>:[主题 ,分类,日期,内容]等.
 * 
 * @param blogURL
 * @return
 * @throws Exception
 */
public static String[] extractBlogInfo(String blogURL) throws Exception {
	String[] info = new String[4];
	org.jsoup.nodes.Document doc = Jsoup.connect(blogURL).get();
	org.jsoup.nodes.Element e_title = doc.select("h2.title").first();
	info[0] = e_title.text();

	org.jsoup.nodes.Element e_category = doc.select("a[rel=category tag]")
			.first();
	info[1] = e_category.attr("href").replace("http://www.micmiu.com/", "");

	org.jsoup.nodes.Element e_date = doc.select("span.post-info-date")
			.first();

	String dateStr = e_date.text().split("日期")[1].trim();
	info[2] = dateStr;
	org.jsoup.nodes.Element entry = doc.select("div.entry").first();
	info[3] = formatContentTag(entry);

	return info;
}
 
Example 12
Project: DWSurvey   File: ItextpdfTest.java   View source code 6 votes vote down vote up
public static void writeSimplePdf() throws Exception{
			//1.新建document对象
			//第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
			Document document = new Document(PageSize.A4, 50, 50, 50, 50);
			//2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
			//创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
			PdfWriter writer = PdfWriter.getInstance(document, 	new FileOutputStream("D:\\Documents\\ITextTest.pdf"));
			//3.打开文档
			document.open();		
			//4.向文档中添加内容
			//通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落
			BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			Font fontChinese = new Font(bfChinese, 22, Font.BOLD, BaseColor.BLACK);
			
			document.add(new Paragraph("sdfsdfsd全是中文显示了没.fsdfsfs",fontChinese));
			document.add(new Paragraph("Some more text on the 	first page with different color and font type.",
					FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new BaseColor(255, 150, 200))));
			Paragraph pragraph=new Paragraph("你这里有中亠好", fontChinese);
			document.add(pragraph);
			
			//图像支持格式 GIF, Jpeg, PNG, wmf
			Image gif = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png");
			gif.setBorder(5);
			gif.scaleAbsolute(30,30);
			gif.setAlignment(Image.RIGHT|Image.TEXTWRAP);
			document.add(gif);
			Paragraph pragraph11=new Paragraph("你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好", fontChinese);
			document.add(pragraph11);
			
			Image gif15 = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png");
//			gif15.setBorder(50);
			gif15.setBorder(Image.BOX);
			gif15.setBorderColor(BaseColor.RED);
//			gif15.setBorderColorBottom(borderColorBottom)
			gif15.setBorderWidth(1);
			gif15.scalePercent(50);
			document.add(gif15);
			//5.关闭文档
			document.close();
		}
 
Example 13
Project: DWSurvey   File: Demo4URL2PDF.java   View source code 6 votes vote down vote up
/**
 * 根据URL提前blog的基本信息,返回结果>>:[主题 ,分类,日期,内容]等.
 * 
 * @param blogURL
 * @return
 * @throws Exception
 */
public static String[] extractBlogInfo(String blogURL) throws Exception {
	String[] info = new String[4];
	org.jsoup.nodes.Document doc = Jsoup.connect(blogURL).get();
	org.jsoup.nodes.Element e_title = doc.select("h2.title").first();
	info[0] = e_title.text();

	org.jsoup.nodes.Element e_category = doc.select("a[rel=category tag]")
			.first();
	info[1] = e_category.attr("href").replace("http://www.micmiu.com/", "");

	org.jsoup.nodes.Element e_date = doc.select("span.post-info-date")
			.first();

	String dateStr = e_date.text().split("日期")[1].trim();
	info[2] = dateStr;
	org.jsoup.nodes.Element entry = doc.select("div.entry").first();
	info[3] = formatContentTag(entry);

	return info;
}
 
Example 14
Project: bdf2   File: PdfReportPageNumber.java   View source code 6 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 15
Project: Spring-MVC-Blueprints   File: AbstractPdfView.java   View source code 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception  {
	// IE workaround: write into byte array first.
			ByteArrayOutputStream baos = createTemporaryOutputStream();

			// Apply preferences and build metadata.
			Document document = new Document();
			PdfWriter writer = PdfWriter.getInstance(document, baos);
			prepareWriter(model, writer, request);
			buildPdfMetadata(model, document, request);

			// Build PDF document.
			writer.setInitialLeading(16);
			document.open();
			buildPdfDocument(model, document, writer, request, response);
			document.close();

			// Flush to HTTP response.
			writeToResponse(response, baos);

	
}
 
Example 16
Project: Spring-MVC-Blueprints   File: HRPDFBuilder.java   View source code 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = createTemporaryOutputStream();
 
    // Apply preferences and build metadata.
    Document document = newDocument();
    PdfWriter writer = newWriter(document, baos);
    prepareWriter(model, writer, request);
    buildPdfMetadata(model, document, request);
 
    // Build PDF document.
    document.open();
    buildPdfDocument(model, document, writer, request, response);
    document.close();
 
    // Flush to HTTP response.
    writeToResponse(response, baos);
}
 
Example 17
Project: OSCAR-ConCert   File: Doc2PDF.java   View source code 6 votes vote down vote up
public static String GetPDFBin(HttpServletResponse response, String docText) {
    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        InputStream is = new ByteArrayInputStream(docText.getBytes());
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
        document.close();
        return(new String(Base64.encodeBase64(baos.toByteArray())));
    }
    catch (Exception e) {
    	logger.error("Unexpected error", e);
    }
    return null;

}
 
Example 18
Project: OSCAR-ConCert   File: Doc2PDF.java   View source code 6 votes vote down vote up
public static void PrintPDFFromHTMLString(HttpServletResponse response, String docText) {
    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        InputStream is = new ByteArrayInputStream(docText.getBytes());
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
        document.close();
        byte[] binArray = baos.toByteArray();
        PrintPDFFromBytes(response, binArray);
    }
    catch (Exception e) {
    	logger.error("Unexpected error", e);
    }
}
 
Example 19
Project: simbest-cores   File: PdfBuilder.java   View source code 6 votes vote down vote up
public Document createDocument(File pdfFile) throws DocumentException, IOException{
		Document document = new Document(new Rectangle(pageWidth, pageHeight));
		document.setPageSize(PageSize.A4);
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
		//写入页尾
		this.setFooter(writer); 
		writer.setFullCompression();
		writer.setPdfVersion(PdfWriter.VERSION_1_4);
		document.open();	
//		//加入二维码图片
//		Image image = Image.getInstance(System.getProperty(appConfig.getValue("app.root"))+"/images/logoqrcode.png");
//        image.scaleAbsolute(40,40);//控制图片大小
//        image.setAlignment(Image.LEFT);
//        document.add(image);
        return document;
	}
 
Example 20
Project: simbest-cores   File: HeaderFooter.java   View source code 6 votes vote down vote up
/**
 * 
 * TODO 关闭文档时,替换模板,完成整个页眉页脚组件
 * 
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
 *      com.itextpdf.text.Document)
 */
public void onCloseDocument(PdfWriter writer, Document document) {
	// 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
	total.beginText();
	total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
	String foot2 = " " + (writer.getPageNumber() - 1) + " 页";
	total.showText(foot2);// 模版显示的内容
	total.endText();
	total.closePath();
}
 
Example 21
Project: Voting_2b   File: PDFLetterWriter.java   View source code 6 votes vote down vote up
private void putPdfInfo(Document document) {
	document.addAuthor("AswCensuses2B");
	document.addCreationDate();
	document.addCreator("AswCensuses2B.com");
	document.addTitle("Personal Voter Letter");
	document.addSubject("A pdf file with your password and user at the online service.");
}
 
Example 22
Project: hotel   File: ResidenceService.java   View source code 6 votes vote down vote up
private void addOfferInstances(List<OfferInstance> offerInstances, Document document, BaseFont bf)
		throws DocumentException {

	if(offerInstances.isEmpty()) {
		return;
	}

	document.add(new Paragraph("Wybrane oferty: ", new Font(bf, 12)));

	PdfPTable offerInstancesTable = new PdfPTable(3);
	offerInstancesTable.setWidthPercentage(100);
	offerInstancesTable.setSpacingBefore(18f);
	offerInstancesTable.setSpacingAfter(18f);
	createofferInstancesTableHeaders(offerInstancesTable);
	createofferInstancesTableContent(offerInstances, offerInstancesTable);
	document.add(offerInstancesTable);
}
 
Example 23
Project: coj-web   File: PDFExportProblem.java   View source code 6 votes vote down vote up
public Document getPDF() throws Exception {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(FILE + problem.getPid() + ".pdf"));
    Image image = Image.getInstance(this.logo);
    document.open();
    document.add(image);
    document.addCreationDate();
    document.add(new Paragraph("Title: "+problem.getTitle()));
    document.add(new Paragraph("Code: "+problem.getPid()));
    document.add(new Paragraph(" "));
    document.add(addParagraph("Description",problem.getDescription(), true));
    document.add(addParagraph("Input",problem.getInput(), true));
    document.add(addParagraph("Output",problem.getOutput(), true));
    document.add(addParagraph("Input Example",problem.getInputex().replaceAll("<br/>", ""), true));
    document.add(addParagraph("Output Example",problem.getOutputex(), true));
    document.add(new Paragraph("Time(ms): "+problem.getTime()));
    document.add(new Paragraph("Memory(kb): "+problem.getMemory()));
    document.add(new Paragraph("Source(kb): "+problem.getFontsize()));
    document.addTitle("Challenger Online Judge");
    document.addAuthor("Chjudge");
    document.close();
    return document;
}
 
Example 24
Project: ephesoft   File: PDFUtil.java   View source code 6 votes vote down vote up
/**
 * The <code>closePassedStream</code> method closes the stream passed.
 * 
 * @param reader {@link PdfReader}
 * @param document {@link Document}
 * @param contentByte {@link PdfContentByte}
 * @param writer {@link PdfWriter}
 * @param fileInputStream {@link FileInputStream}
 * @param fileOutputStream {@link FileOutputStream}
 * @throws IOException {@link} if unable to close input or output stream
 */
private static void closePassedStream(final PdfReader reader, final Document document,
		final PdfContentByte contentByte, final PdfWriter writer,
		final FileInputStream fileInputStream, final FileOutputStream fileOutputStream) throws IOException {
	if (null != reader) {
		reader.close();
	} 
	if (null != document) {
		document.close();
	}
	if (null != contentByte) {
		contentByte.closePath();
	}
	if (null != writer) {
		writer.close();
	}
	if (null != fileInputStream) {
		fileInputStream.close();
	}
	
	if (null != fileOutputStream) {
		fileOutputStream.flush();
		fileOutputStream.close();
	}
}
 
Example 25
Project: Desktop   File: Textpdf.java   View source code 6 votes vote down vote up
public void createPdf(String filename,String text)
	throws DocumentException, IOException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
////        BaseColor col=null;
//        if(NewDjvu.textArea.getForeground()==Color.red||NewDjvuFromClib.textAreaClip.getForeground()==Color.red){
//            col=BaseColor.RED;
//        }
//       Font font=new Font(Font.FontFamily.HELVETICA, DjvuComponents.font.getSize(), DjvuComponents.font.getStyle(),col);
////        for (String booksfile1 : booksfile) {
            document.add(new Paragraph(text));
//        }
        // step 5
        document.close();
    }
 
Example 26
Project: OpenSongTablet   File: ExportPreparer.java   View source code 6 votes vote down vote up
private static void makePDF(Bitmap bmp, File file) {
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addAuthor(FullscreenActivity.mAuthor.toString());
        document.addTitle(FullscreenActivity.mTitle.toString());
        document.addCreator("OpenSongApp");
        if (bmp!=null && bmp.getWidth()>bmp.getHeight()) {
            document.setPageSize(PageSize.A4.rotate());
        } else {
            document.setPageSize(PageSize.A4);
        }
        document.addTitle(FullscreenActivity.mTitle.toString());
        document.open();//document.add(new Header("Song title",FullscreenActivity.mTitle.toString()));
        BaseFont urName = BaseFont.createFont("assets/fonts/Lato-Reg.ttf", "UTF-8",BaseFont.EMBEDDED);
        Font TitleFontName  = new Font(urName, 14);
        Font AuthorFontName = new Font(urName, 10);
        document.add(new Paragraph(FullscreenActivity.mTitle.toString(),TitleFontName));
        document.add(new Paragraph(FullscreenActivity.mAuthor.toString(),AuthorFontName));
        addImage(document,bmp);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 27
Project: osdq-core   File: DataDictionaryPDF.java   View source code 6 votes vote down vote up
private void addTitlePage(Document document) throws DocumentException {

	addEmptyLine(document, 5);
   
   Paragraph title = new Paragraph("Data Dictionary by Arrah technology");
   title.setAlignment(Element.ALIGN_CENTER);
   document.add(title);
   addEmptyLine(document, 1);
   
   Paragraph url = new Paragraph("http://sourceforge.net/projects/dataquality/");
   url.setAlignment(Element.ALIGN_CENTER);
   document.add(url);
   addEmptyLine(document, 3);
   
   Paragraph rtime = new Paragraph("Report generated on: " +  new Date());
   rtime.setAlignment(Element.ALIGN_CENTER);
   document.add(rtime);

   document.newPage();
 }
 
Example 28
Project: tellervo   File: PageNumbersWatermark.java   View source code 6 votes vote down vote up
/**
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
public void onStartPage(PdfWriter writer, Document document) {
    if (writer.getPageNumber() < 3) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(BaseColor.PINK);
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        cb.showTextAligned(Element.ALIGN_CENTER, "My Watermark Under " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
}
 
Example 29
Project: testarea-itext5   File: TableWithSpan.java   View source code 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40947306/strange-setrowspan-error-not-working">
 * Strange setRowspan error/not working
 * </a>
 * <p>
 * Selecting 1 header row and having a cell in the first row which spans 2 rows
 * does not match. iText ignores the row span resulting in the weird appearance.
 * </p>
 */
@Test
public void testRowspanWithHeaderRows() throws IOException, DocumentException
{
    File file = new File(RESULT_FOLDER, "rowspanWithHeaderRows.pdf");
    OutputStream os = new FileOutputStream(file);

    Document document = new Document();
    /*PdfWriter writer =*/ PdfWriter.getInstance(document, os);
    document.open();

    document.add(createHeaderContent());
    document.newPage();
    document.add(createHeaderContent(new int[] {5,5,5,5,5}));

    document.close();
}
 
Example 30
Project: tellervo   File: PageNumbersWatermark.java   View source code 6 votes vote down vote up
/**
 * Generates a document with a header containing Page x of y and with a Watermark on every page.
 * @param args no arguments needed
 */
public static void main(String args[]) {
    try {
    	// step 1: creating the document
        Document doc = new Document(PageSize.A4, 50, 50, 100, 72);
        // step 2: creating the writer
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("pageNumbersWatermark.pdf"));
        // step 3: initialisations + opening the document
        writer.setPageEvent(new PageNumbersWatermark());
        doc.open();
        // step 4: adding content
        String text = "some padding text ";
        for (int k = 0; k < 10; ++k)
            text += text;
        Paragraph p = new Paragraph(text);
        p.setAlignment(Element.ALIGN_JUSTIFIED);
        doc.add(p);
        // step 5: closing the document
        doc.close();
    }
    catch ( Exception e ) {
        e.printStackTrace();
    }
}
 
Example 31
Project: testarea-itext5   File: ColorParagraphBackground.java   View source code 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 32
Project: testarea-itext5   File: DoubleSpace.java   View source code 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35699167/double-space-not-being-preserved-in-pdf">
 * Double space not being preserved in PDF
 * </a>
 * <p>
 * Indeed, the double space collapses into a single one when copying&pasting from the
 * generated PDF displayed in Adobe Reader. On the other hand the gap for the double
 * space is twice as wide as for the single space. So this essentially is a quirk of
 * copy&paste of Adobe Reader (and some other PDF viewers, too).
 * </p>
 */
@Test
public void testDoubleSpace() throws DocumentException, IOException
{
    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "DoubleSpace.pdf")))
    {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorderWidth(0.5f);
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);

        table.addCell(new Phrase("SINGLE SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("DOUBLE  SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("TRIPLE   SPACED", new Font(BaseFont.createFont(), 36)));

        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();
        pdfDocument.add(table);
        pdfDocument.close();
    }
}
 
Example 33
Project: testarea-itext5   File: ChangeMargins.java   View source code 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 34
Project: testarea-itext5   File: CreateAndAppendDoc.java   View source code 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 35
Project: testarea-itext5   File: DenseMerging.java   View source code 6 votes vote down vote up
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 0; i < paragraphCount; i++)
    {
        Paragraph paragraph = new Paragraph();
        paragraph.add(String.format(paragraphFormat, i));
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
 
Example 36
Project: testarea-itext5   File: VeryDenseMerging.java   View source code 6 votes vote down vote up
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, baos);
    document.open();
    for (int i = 0; i < paragraphCount; i++)
    {
        Paragraph paragraph = new Paragraph();
        paragraph.add(String.format(paragraphFormat, i));
        document.add(paragraph);
    }
    document.close();

    return baos.toByteArray();
}
 
Example 37
Project: testarea-itext5   File: VeryDenseMerging.java   View source code 6 votes vote down vote up
static byte[] createSimpleCircleGraphicsPdf(int radius, int gap, int count) throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    float y = writer.getPageSize().getTop();
    for (int i = 0; i < count; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        if (y <= pageSize.getBottom() + 2*radius)
        {
            y = pageSize.getTop();
            writer.getDirectContent().fillStroke();
            document.newPage();
        }
        writer.getDirectContent().circle(pageSize.getLeft() + pageSize.getWidth() * Math.random(), y-radius, radius);
        y-= 2*radius + gap;
    }
    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}
 
Example 38
Project: testarea-itext5   File: CopyForm.java   View source code 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32710839/itextsharp-pdfcopy-makes-read-only-fields-editable">
 * iTextSharp PdfCopy makes read-only fields editable
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/nhy7av9b37uwowl/in1.pdf?dl=0">
 * in1.pdf
 * </a>
 * <p>
 * Indeed, the issue can be reproduced. A possible explanation in a SO answer.
 * </p> 
 */
@Test
public void testCopyReadOnlyFields() throws IOException, DocumentException
{
    Document document = new Document();
    
    try (   OutputStream fileStream = new FileOutputStream(new File(RESULT_FOLDER, "in1Copy.pdf"));
            InputStream resource = getClass().getResourceAsStream("in1.pdf")    )
    {
        PdfCopy copier = new PdfCopy(document, fileStream);
        PdfReader reader = new PdfReader(resource);

        copier.setMergeFields();
        document.open();
        copier.addDocument(reader);
        copier.addJavaScript(reader.getJavaScript());
        document.close();
    }
}
 
Example 39
Project: Briss-2.0   File: CropManager.java   View source code 6 votes vote down vote up
private static File copyToMultiplePages(CropJob cropJob) throws IOException, DocumentException {

		PdfReader reader = new PdfReader(cropJob.getSource().getAbsolutePath());
		Document document = new Document();

		File resultFile = File.createTempFile("cropped", ".pdf");
		PdfSmartCopy pdfCopy = new PdfSmartCopy(document, new FileOutputStream(resultFile));
		document.open();
		PdfImportedPage page;

		for (int pageNumber = 1; pageNumber <= cropJob.getSourcePageCount(); pageNumber++) {
			SingleCluster currentCluster = cropJob.getClusterCollection().getSingleCluster(pageNumber);
			page = pdfCopy.getImportedPage(reader, pageNumber);
			pdfCopy.addPage(page);
			for (int j = 1; j < currentCluster.getRatiosList().size(); j++) {
				pdfCopy.addPage(page);
			}
		}
		document.close();
		pdfCopy.close();
		reader.close();
		return resultFile;
	}
 
Example 40
Project: testarea-itext5   File: ImportPageWithoutFreeSpace.java   View source code 6 votes vote down vote up
/**
 * This method creates a PDF with a single styled paragraph.
 */
static byte[] createSimpleCircleGraphicsPdf() throws DocumentException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    float y = writer.getPageSize().getTop(document.topMargin());
    float radius = 20;
    for (int i = 0; i < 3; i++)
    {
        Rectangle pageSize = writer.getPageSize();
        writer.getDirectContent().circle(
                pageSize.getLeft(document.leftMargin()) + (pageSize.getWidth() - document.leftMargin() - document.rightMargin()) * Math.random(),
                y-radius, radius);
        y-= 2*radius + 5;
    }

    writer.getDirectContent().fillStroke();
    document.close();

    return baos.toByteArray();
}