当前位置: 首页>>代码示例>>Java>>正文


Java ITextRenderer.layout方法代码示例

本文整理汇总了Java中org.xhtmlrenderer.pdf.ITextRenderer.layout方法的典型用法代码示例。如果您正苦于以下问题:Java ITextRenderer.layout方法的具体用法?Java ITextRenderer.layout怎么用?Java ITextRenderer.layout使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.xhtmlrenderer.pdf.ITextRenderer的用法示例。


在下文中一共展示了ITextRenderer.layout方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: generatePdf

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
@Override
@Nullable
public byte[] generatePdf(@NonNull final String _html) {
    try {
        final ITextRenderer renderer = new ITextRenderer();
        final ITextFontResolver fontResolver = renderer.getFontResolver();

        final ClassPathResource regular = new ClassPathResource("fonts/LiberationSerif-Regular.ttf");
        fontResolver.addFont(regular.getURL().toString(), BaseFont.IDENTITY_H, true);

        renderer.setDocumentFromString(_html);
        renderer.layout();

        @Cleanup final ByteArrayOutputStream os = new ByteArrayOutputStream();
        renderer.createPDF(os);

        return os.toByteArray();
    } catch(Exception _e) {
        log.error("Failed to generate PDF", _e);
        return null;
    }
}
 
开发者ID:jonfryd,项目名称:tifoon,代码行数:23,代码来源:ReportGeneratorServiceImpl.java

示例2: exportPdfFile

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
public static File exportPdfFile(String urlStr) throws Exception {
	// String outputFile = this.fileRoot + "/" +
	// ServiceConstants.DIR_PUBINFO_EXPORT + "/" + getFileName() + ".pdf";
	String outputFile = "D:/Documents/test3.pdf";
	OutputStream os = new FileOutputStream(outputFile);
	ITextRenderer renderer = new ITextRenderer();

	String str = getHtmlFile(urlStr);
	renderer.setDocumentFromString(str);
	ITextFontResolver fontResolver = renderer.getFontResolver();

	fontResolver.addFont("F:/keyworkspace/survey/src/conf/itextpdf/simsun.ttc",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
	// // 宋体字
	fontResolver.addFont("F:/keyworkspace/survey/src/conf/itextpdf/ARIALUNI.TTF",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 宋体字
	renderer.layout();

	renderer.createPDF(os);

	os.flush();
	os.close();
	return new File(outputFile);

}
 
开发者ID:wkeyuan,项目名称:DWSurvey,代码行数:24,代码来源:PDFUtil.java

示例3: renderToPDF

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
public static byte[] renderToPDF(String orig_html) throws Exception {
    File html_file = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ITextRenderer renderer = new ITextRenderer();

        html_file = prepareTempHTML(orig_html);
        renderer.setDocument(html_file);
        renderer.layout();
        renderer.createPDF(baos);

        return baos.toByteArray();
    } finally {
        if (html_file != null) {
            html_file.delete();
        }
    }
}
 
开发者ID:schmave,项目名称:demschooltools,代码行数:19,代码来源:Application.java

示例4: convert

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
@Override
public byte[] convert(String input) throws ConversionException {
    try {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(new String(input.getBytes()));
        renderer.layout();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        renderer.createPDF(outputStream);
        byte[] bytes = outputStream.toByteArray();
        return bytes;
    } catch (DocumentException e) {
        e.printStackTrace();
        throw ConversionException.HTML_TO_PDF_EXCEPTION;
    }
}
 
开发者ID:eamonfoy,项目名称:trello-to-markdown,代码行数:16,代码来源:Html2PdfConverter.java

示例5: convertHTMLtoPDF

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
public static byte[] convertHTMLtoPDF(InputStream bais, boolean isFitWidth) throws ParserConfigurationException, SAXException, IOException, DocumentException {
        ITextRenderer renderer = new ITextRenderer();
//		renderer.getFontResolver().addFont("calibri.ttf", true);
        renderer.setScaleToFit(isFitWidth);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource(bais);
        Document doc = builder.parse(is);

        renderer.setDocument(doc, null);

        renderer.layout();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        renderer.createPDF(out);
        out.flush();
        out.close();

        return out.toByteArray();
    }
 
开发者ID:rmage,项目名称:gnvc-ims,代码行数:20,代码来源:ReportModel.java

示例6: renderPdfDocument

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
protected void renderPdfDocument(String htmlContent, OutputStream outputStream) {
    ITextRenderer renderer = new ITextRenderer();
    File temporaryFile = null;
    try {
        temporaryFile = File.createTempFile("htmlReport", ".htm");
        DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(temporaryFile));
        dataOutputStream.write(htmlContent.getBytes(Charset.forName("UTF-8")));
        dataOutputStream.close();

        loadFonts(renderer);

        String url = temporaryFile.toURI().toURL().toString();
        renderer.setDocument(url);

        renderer.layout();
        renderer.createPDF(outputStream);
    } catch (Exception e) {
        throw wrapWithReportingException("", e);
    } finally {
        FileUtils.deleteQuietly(temporaryFile);
    }
}
 
开发者ID:cuba-platform,项目名称:yarg,代码行数:23,代码来源:HtmlFormatter.java

示例7: createPdf

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
public static void createPdf(String content, String dest)
		throws IOException, DocumentException, com.lowagie.text.DocumentException {
	ITextRenderer render = new ITextRenderer();
	ITextFontResolver fontResolver = render.getFontResolver();
	fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
	// 解析html生成pdf
	render.setDocumentFromString(content);
	// 解决图片相对路径的问题
	render.getSharedContext().setBaseURL(LOGO_PATH);
	render.layout();
	render.createPDF(new FileOutputStream(dest));
}
 
开发者ID:Sunny0715,项目名称:java_pdf_demo,代码行数:13,代码来源:JavaToPdfHtmlFreeMarker.java

示例8: generatePdf

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
private ITextRenderer generatePdf(String templatePath, Map<String, Object> model) throws FileNotFoundException, IOException, DocumentException, TemplateException {
	if (templatePath ==null || "".equals(templatePath) || model ==null){
		return null;
	}
       
	fmConfig.setDefaultEncoding("UTF-8");
	fmConfig.setClassForTemplateLoading(this.getClass(), "/");
	String resourcePath = getResourcePath();
	fmConfig.setSharedVariable("base", resourcePath);
       Template template = fmConfig.getTemplate(templatePath);
       
	StringWriter result = new StringWriter();
	template.process(model, result);
	String content = result.toString();
	//String content = FreeMarkers.renderTemplate(template, model);//<#assign fmt=JspTaglibs["/WEB-INF/tlds/fmt.tld"]><@fmt.message key="label.fn.compnt.name"/> 
	
       ITextRenderer renderer = new ITextRenderer();

       ITextFontResolver fontResolver = renderer.getFontResolver(); 
       fontResolver.addFont(resourcePath.concat("/report/resource/font/MSYH.TTF"), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); 
       fontResolver.addFont(resourcePath.concat("/report/resource/font/ARIAL.TTF"), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); 
       
       //Image Path
       //renderer.getSharedContext().setBaseURL(resourcePath.concat("/report/resource/image")); 
       //renderer.getSharedContext().setUserAgentCallback(new HttpURLUserAgent(renderer.getOutputDevice()));  

       renderer.setDocumentFromString(content);
       renderer.layout(); 
       log.debug("Generate Pdf as ITextRenderer Successfully.");
       return renderer;
}
 
开发者ID:Jawf,项目名称:reportJ,代码行数:32,代码来源:XhtmlPdfGenerator.java

示例9: createPDF

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
@Override
public byte[] createPDF(byte[] documentSource, String url) {
  try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
    ITextRenderer renderer = initRenderer();

    Document document = load(new ByteArrayInputStream(documentSource)).getDocument();
    renderer.setDocument(document, url);
    renderer.layout();
    renderer.createPDF(os);

    return os.toByteArray();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
开发者ID:tunguski,项目名称:matsuo-core,代码行数:16,代码来源:PrintsRendererService.java

示例10: writePDFFromXHTML

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
public static synchronized void writePDFFromXHTML(
  final String  pdfFilePath,
  final String  xhtmlFilePath,
  final boolean useImageEmbedder) throws SSErr{
  
  FileOutputStream out = null;
  
  try{
    
    final ITextRenderer renderer = new ITextRenderer();
    final String        uri      = new File(xhtmlFilePath).toURI().toURL().toString();
    
    out = new FileOutputStream(pdfFilePath);
    
    if(useImageEmbedder){
      renderer.getSharedContext().setReplacedElementFactory(
        new SSPDFFromXHTMLImageEmbedder(
          renderer.getSharedContext().getReplacedElementFactory()));
    }
    
    renderer.setDocument(uri);
    renderer.layout(); //can happen http://stackoverflow.com/questions/13678641/while-converting-xhtml-with-css-to-pdf-got-an-exception-java-lang-indexoutofboun
    renderer.createPDF(out);
  }catch(Exception error){
    SSServErrReg.regErrThrow(error);
  }finally{
    
    if(out != null){
      try {
        out.close();
      } catch (IOException ex) {
        SSLogU.err(ex);
      }
    }
  }
}
 
开发者ID:learning-layers,项目名称:SocialSemanticServer,代码行数:37,代码来源:SSFileU.java

示例11: preparePageCounters

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
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 ){}
	}
}
 
开发者ID:OpenBD,项目名称:openbd-core,代码行数:42,代码来源:cfDOCUMENT.java

示例12: main

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
public static void main(String[] args) throws IOException, ParserConfigurationException, DocumentException
   {
       if (args.length != 2)
       {
           System.out.println("Error: You should type as: convertToPDF htmlFile pdfOut");
           System.exit(1);
       }

       String htmlFile = args[0];
       String pdfOutFile = args[1];//"/home/sardor/Downloads/CV_B/test.pdf";

       FileInputStream input = reOpenStream(htmlFile);


       //Append required HTML elements via JSoup
       HtmlValidator validator = new HtmlValidator(input, htmlFile);
       if(validator.hasError()==1)
       {
           System.out.println("Error: Something wrong with HTML file");
           System.exit(1);
       }

       //Redefine file stream
       input = reOpenStream(htmlFile);

       //Validate out html document
       Tidy tidy=new Tidy();
       tidy.setInputEncoding("UTF-8");
       tidy.setOutputEncoding("UTF-8");
       tidy.setIndentCdata(true);
       tidy.setQuiet(true);
       tidy.setForceOutput(true);
       tidy.setTidyMark(false);
       tidy.setXHTML(true);
       tidy.setJoinClasses(true);
       tidy.setSmartIndent(true);

       //Convert to XML view
       Document xhtmlDoc = tidy.parseDOM(input, null);

       //Create PDF file
       OutputStream os = new FileOutputStream(pdfOutFile);

       //Render pdf doc
       ITextRenderer renderer = new ITextRenderer();
       renderer.setDocument(xhtmlDoc,null);
       renderer.layout();
       renderer.createPDF(os);

       os.close();
}
 
开发者ID:snavruzov,项目名称:HTML2PDF,代码行数:52,代码来源:Html2PDF.java

示例13: createBasePDF

import org.xhtmlrenderer.pdf.ITextRenderer; //导入方法依赖的package包/类
private File createBasePDF(Node node, List<PDFManagerResponse> managerResponses, FlowInstanceManager instanceManager, FlowInstanceEvent event) throws DocumentException, IOException {

		File basePDF = File.createTempFile("basepdf", instanceManager.getFlowInstanceID() + "-" + getFileSuffix(event) + ".pdf", getTempDir());

		OutputStream basePDFOutputStream = null;

		try{
			basePDFOutputStream = new FileOutputStream(basePDF);

			ITextRenderer renderer = new ITextRenderer();
			ResourceLoaderAgent callback = new ResourceLoaderAgent(renderer.getOutputDevice(), managerResponses);
			callback.setSharedContext(renderer.getSharedContext());
			renderer.getSharedContext().setUserAgentCallback(callback);

			if(this.fontList != null){

				for(String font : fontList){

					renderer.getFontResolver().addFont(font, true);
				}
			}

			renderer.setDocument((Document)node, "c:\\users\\unlogic\foo.html");
			renderer.layout();

			renderer.createPDF(basePDFOutputStream);

		}finally{

			StreamUtils.closeStream(basePDFOutputStream);
		}

		return basePDF;
	}
 
开发者ID:Sundsvallskommun,项目名称:Open-ePlatform,代码行数:35,代码来源:PDFGeneratorModule.java


注:本文中的org.xhtmlrenderer.pdf.ITextRenderer.layout方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。