org.xhtmlrenderer.pdf.ITextRenderer Java Examples

The following examples show how to use org.xhtmlrenderer.pdf.ITextRenderer. 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: cfDOCUMENT.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
private void resolveFonts( cfSession _Session, ITextRenderer _renderer ) throws dataNotSupportedException, cfmRunTimeException{
	ITextFontResolver resolver = _renderer.getFontResolver();
	
	boolean embed = getDynamic( _Session, "FONTEMBED" ).getBoolean();
	for ( int i = 0; i < defaultFontDirs.length; i++ ){
		File nextFontDir = new File( defaultFontDirs[i] );
		File[] fontFiles = nextFontDir.listFiles( new FilenameFilter() {
			public boolean accept( File _dir, String _name ){
				String name = _name.toLowerCase();
				return name.endsWith( ".otf" ) || name.endsWith( ".ttf" );
			}
     });
		if ( fontFiles != null ){
      for ( int f = 0; f < fontFiles.length; f++ ){
      	try{
      		resolver.addFont( fontFiles[f].getAbsolutePath(), BaseFont.IDENTITY_H,
  	          embed );
      	}catch( Exception ignored ){} // ignore fonts that can't be added
      }
		}
	}
}
 
Example #2
Source File: cfDOCUMENT.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void onClose(ITextRenderer renderer) 
{
	PdfString creator = new PdfString("OpenBD " + cfEngine.PRODUCT_VERSION + " (" + cfEngine.BUILD_ISSUE + ")");
	renderer.getOutputDevice().getWriter().getInfo().put(PdfName.CREATOR,creator);  
	
	if (author != null)
		renderer.getOutputDevice().getWriter().getInfo().put(PdfName.AUTHOR,author);  
	if (title != null)
		renderer.getOutputDevice().getWriter().getInfo().put(PdfName.TITLE,title);  
	if (subject != null)
		renderer.getOutputDevice().getWriter().getInfo().put(PdfName.SUBJECT,subject);  
	if (keywords != null)
		renderer.getOutputDevice().getWriter().getInfo().put(PdfName.KEYWORDS,keywords);  
}
 
Example #3
Source File: PDFThymeleafExample.java    From tutorials with MIT License 5 votes vote down vote up
public void generatePdfFromHtml(String html) throws IOException, DocumentException {
    String outputFolder = System.getProperty("user.home") + File.separator + "thymeleaf.pdf";
    OutputStream outputStream = new FileOutputStream(outputFolder);

    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(html);
    renderer.layout();
    renderer.createPDF(outputStream);

    outputStream.close();
}
 
Example #4
Source File: GeneratePDFWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        Map<String, Object> results = new HashMap<>();
        String templateXHTML = (String) workItem.getParameter("TemplateXHTML");
        String pdfName = (String) workItem.getParameter("PDFName");

        if (pdfName == null || pdfName.isEmpty()) {
            pdfName = "generatedpdf";
        }

        Configuration cfg = new Configuration(freemarker.template.Configuration.VERSION_2_3_26);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);

        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("pdfTemplate",
                                 templateXHTML);
        cfg.setTemplateLoader(stringLoader);

        StringWriter stringWriter = new StringWriter();

        Template pdfTemplate = cfg.getTemplate("pdfTemplate");
        pdfTemplate.process(workItem.getParameters(),
                            stringWriter);
        resultXHTML = stringWriter.toString();

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(resultXHTML);
        renderer.layout();

        Document document = new DocumentImpl();
        document.setName(pdfName + ".pdf");
        document.setLastModified(new Date());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        renderer.createPDF(baos);
        document.setContent(baos.toByteArray());

        results.put(RESULTS_VALUE,
                    document);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error(e.getMessage());
        handleException(e);
    }
}
 
Example #5
Source File: cfDOCUMENT.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public cfTagReturnType render( cfSession _Session ) throws cfmRunTimeException {		
	
	if ( !getDynamic( _Session, "FORMAT" ).getString().equalsIgnoreCase( "PDF" ) ){
		throw newRunTimeException( "Invalid FORMAT value. Only \"PDF\" is supported." );
	}
	
	if ( containsAttribute( "SRC" ) && containsAttribute( "SRCFILE" ) ){
		throw newRunTimeException( "Invalid attribute combination. Either the SRC or SRCFILE attribute must be specified but not both" );
	}
	
	ITextRenderer renderer = new ITextRenderer();
	CreationListener listener = new CreationListener(getDynamic(_Session, "AUTHOR"),getDynamic(_Session, "TITLE"),getDynamic(_Session, "SUBJECT"),getDynamic(_Session, "KEYWORDS"));
	renderer.setListener(listener);
	resolveFonts( _Session, renderer );
	
	if ( _Session.getDataBin( CFDOCUMENT_KEY ) != null ){
		throw newRunTimeException( "CFDOCUMENT cannot be embedded within another CFDOCUMENT tag" );
	}
	
	_Session.setDataBin( CFDOCUMENT_KEY, new DocumentContainer() );

	String renderedBody = renderToString( _Session ).getOutput();
	try{
		DocumentContainer container = (DocumentContainer) _Session.getDataBin( CFDOCUMENT_KEY );
		
		List<DocumentSection> sections = container.getSections(); 
		if ( sections.size() == 0 ){
			// if no sections are specified then construct one from this tag
			DocumentSection section = new DocumentSection();
			section.setHeader( container.getMainHeader(), container.getMainHeaderAlign() );
			section.setFooter( container.getMainFooter(), container.getMainFooterAlign() );
			
			if ( renderedBody.length() == 0 && !( containsAttribute( "SRC" ) || containsAttribute( "SRCFILE" ) ) ){
				throw newRunTimeException( "Cannot create a PDF from an empty document!" );	
			}
			
			String src = containsAttribute( "SRC" ) ? getDynamic( _Session, "SRC" ).getString() : null;
			String srcFile = containsAttribute( "SRCFILE" ) ? getDynamic( _Session, "SRCFILE" ).getString() : null;
			
			section.setSources( src, srcFile, renderedBody );
			appendSectionAttributes( _Session, section );
			
			sections.add( section );
		}

		DocumentSettings settings = getDocumentSettings( _Session, container );

		// If there is more than 1 section and page counters are used that need special
		// processing then we need to do an initial conversion of the HTML to PDF to
		// determine how many pages are created per section and how many pages are created total.
		if ((sections.size() > 1) && (container.usesTotalPageCounters()))
			preparePageCounters( _Session, renderer, sections, settings );

		preparePDF( _Session, renderer, sections, settings );

		return cfTagReturnType.NORMAL;
	}finally{
		_Session.deleteDataBin( CFDOCUMENT_KEY );
	}

}
 
Example #6
Source File: cfDOCUMENT.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
private void preparePageCounters( cfSession _Session, ITextRenderer _renderer, List<DocumentSection> _sections, DocumentSettings _settings ) throws cfmRunTimeException{
	OutputStream pdfOut = null;
	try{
		pdfOut = new NullOutputStream();
		
		DocumentSection nextSection = _sections.get( 0 );
		if (nextSection.pageCounterConflict())
			throw newRunTimeException("OpenBD doesn't support currentpagenumber and currentsectionpagenumber in same section.");		
		String renderedBody = getRenderedBody( _Session, nextSection, _settings, _sections.size() );
		_renderer.setDocument( getDocument( renderedBody ), nextSection.getBaseUrl( _Session ) );
		_renderer.layout();
		_renderer.createPDF( pdfOut, false );
		
		int currentPageNumber = _renderer.getWriter().getCurrentPageNumber();
		nextSection.setTotalSectionPageCount(currentPageNumber);
		int totalPageCount = currentPageNumber;

		for ( int i = 1; i < _sections.size(); i++ ){
			nextSection = _sections.get( i );
			if (nextSection.pageCounterConflict())
				throw newRunTimeException("OpenBD doesn't support currentpagenumber and currentsectionpagenumber in same section.");
			renderedBody = getRenderedBody( _Session, nextSection, _settings, _sections.size() );
			_renderer.setDocument( getDocument( renderedBody ), nextSection.getBaseUrl( _Session ) );
			_renderer.layout();
			_renderer.writeNextDocument( _renderer.getWriter().getCurrentPageNumber()+1 );
			currentPageNumber = _renderer.getWriter().getCurrentPageNumber();
			nextSection.setTotalSectionPageCount(currentPageNumber-totalPageCount);
			totalPageCount = currentPageNumber;
		}
		
		for ( int i = 0; i < _sections.size(); i++ ){
			nextSection = _sections.get( i );
			nextSection.setTotalPageCount(totalPageCount);
		}
	
	} catch (DocumentException e) {
		throw newRunTimeException( "Failed to create PDF due to DocumentException: " + e.getMessage() );
	}finally{
		if ( pdfOut != null )try{ pdfOut.close(); }catch( IOException ignored ){}
	}
}
 
Example #7
Source File: HtmlFormatter.java    From yarg with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated
 * @see #loadFonts(HtmlToPdfConverter)
 */
@Deprecated
protected void loadFonts(ITextRenderer renderer) {
    loadFonts(new ITextPdfConverter(renderer));
}
 
Example #8
Source File: HtmlFormatter.java    From yarg with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated
 * @see #loadFontsFromDirectory(HtmlToPdfConverter, java.io.File)
 */
@Deprecated
protected void loadFontsFromDirectory(ITextRenderer renderer, File fontsDir) {
    loadFontsFromDirectory(new ITextPdfConverter(renderer), fontsDir);
}
 
Example #9
Source File: ITextPdfConverter.java    From yarg with Apache License 2.0 4 votes vote down vote up
public ITextPdfConverter() {
    this(new ITextRenderer());
}
 
Example #10
Source File: ITextPdfConverter.java    From yarg with Apache License 2.0 4 votes vote down vote up
public ITextPdfConverter(ITextRenderer renderer) {
    this.renderer = renderer;
}
 
Example #11
Source File: PDFThymeleafUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
private ByteArrayOutputStream generatePdfOutputStreamFromHtml(String html) throws IOException, DocumentException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(html);
    renderer.layout();
    renderer.createPDF(outputStream);

    outputStream.close();
    return outputStream;
}