将HTML转换为多列PDF

时间:2014-11-10 13:28:39

标签: c# html css3 pdf itext

我正在尝试使用iText for .NET从HTML生成多列PDF。 我使用CSS3语法生成两列。

以下代码对我不起作用。

CSS

column-count:2; 

C#代码

StringReader html = new StringReader(@"
<div style='column-count:2;'>Sample Text. Sample Text. Sample Text. Sample Text. 
Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. 
Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. 
Sample Text. Sample Text. </div>
");

        Document document = new Document();
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"d:\temp\xyz.pdf", FileMode.Create));
        document.Open();
        XMLWorkerHelper.GetInstance().ParseXHtml(
          writer, document, html
        );
        document.Close();

请在此代码中说明问题所在。或者是否有任何其他HTML到PDF库可用于解决此问题。

1 个答案:

答案 0 :(得分:0)

XML Worker中不支持CSS属性column-count,它可能永远不会。

但是,这并不意味着您无法在列中显示HTML。

如果您转到官方的XML Worker文档,您将找到解析大型HTML文件的ParseHtmlObjects,并将其呈现为包含两列的PDF:walden5.pdf

首先将HTML解析为ElementList

// CSS
CSSResolver cssResolver =
        XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
htmlContext.autoBookmark(false);
// Pipelines
ElementList elements = new ElementList();
ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
HtmlPipeline html = new HtmlPipeline(htmlContext, end);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);

获得Element个对象列表后,我们可以将它们添加到ColumnText对象中:

// step 1
Document document = new Document(PageSize.LEGAL.rotate());
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
Rectangle left = new Rectangle(36, 36, 486, 586);
Rectangle right = new Rectangle(522, 36, 972, 586);
ColumnText column = new ColumnText(writer.getDirectContent());
column.setSimpleColumn(left);
boolean leftside = true;
int status = ColumnText.START_COLUMN;
for (Element e : elements) {
    if (ColumnText.isAllowedElement(e)) {
        column.addElement(e);
        status = column.go();
        while (ColumnText.hasMoreText(status)) {
            if (leftside) {
                leftside = false;
                column.setSimpleColumn(right);
            }
            else {
                document.newPage();
                leftside = true;
                column.setSimpleColumn(left);
            }
            status = column.go();
        }
    }
}
// step 5
document.close();

如您所见,您需要在此做出一些决定:您需要在页面上定义矩形。你需要介绍新的页面等...

注意:目前没有此文档的C#端口。请将Java代码视为伪代码。