iTextSharp add ( css style or a css file) and download pdf file

前端 未结 1 846
鱼传尺愫
鱼传尺愫 2020-12-22 08:20

Finally got it working

var inputString = @\"

1条回答
  •  借酒劲吻你
    2020-12-22 08:58

    As you have discovered yourself, the main problem you experienced was caused by feeding invalid HTML to XML Worker. I have written a Java example that is equivalent to your (updated) C# example:

    public static final String CSS = "th { background-color: #C0C0C0; font-size: 16pt; } "
        + "td { font-size: 10pt; }";
    public static final String HTML = "
" + "" + "" + "" + "
Customer NameCustomer's Address
XYZ Bhubaneswar
MNP Cuttack
"; /** * @param file * @throws IOException * @throws DocumentException */ public void createPdf(String file) throws IOException, DocumentException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); CSSResolver cssResolver = new StyleAttrCSSResolver(); CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(CSS.getBytes())); cssResolver.addCss(cssFile); // HTML HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory()); // Pipelines PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer); 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(new ByteArrayInputStream(HTML.getBytes())); document.close(); }

The resulting table looks like this:

You can tweak the values stored in CSS to create a nicer appearance for the table.

0 讨论(0)
提交回复
热议问题