ITextsharp Html2Pdf CSS问题

时间:2018-05-16 14:38:51

标签: html css itext

我是iTextSharp的新手,目前正在使用Html2pdf(iTextSharp扩展名)将HTML转换为PDF。我能够生成pdf,但无法在每个页面上为pdf添加徽标。

图像即将到来,但我无法改变图像的宽度。

CSS我用于pdf徽标的内容如下:

@page { 
@top-left { 
content:"test "; 
background:url(../images/template/test_logo_pdf.jpg) no-repeat 0px 0px;
border:1px solid red;
background-color: #cccccc;

margin-top:10px;
} 
@top-right { 
content: flow(header); 
}
@bottom-right { 
content: "Page " counter(page) " of " counter(pages); 
font: 8pt Arial, sans-serif; 
} 
@bottom-left { 
content: string(repname); 
font: 8pt Arial, sans-serif; 
}
}

1 个答案:

答案 0 :(得分:1)

控制添加到页边距框的图像尺寸确实不容易。我可以建议的一种可能方法是将图像添加为内容(而不是背景图像)并使用自定义标记工作程序,它将根据页面边框框子图像的图像指定高度和宽度:

HTML:

@top-left {  
  content: url(../images/template/test_logo_pdf.jpg);
  border:1px solid red;
  background-color: #cccccc;
  margin-top:10px;
}

这是Java代码,但是.NET版本具有完全相同的API,只是代码风格不同(方法名称开头的大写字母等):

private static class PageMarginBoxImagesTagWorkerFactory extends DefaultTagWorkerFactory {
    @Override
    public ITagWorker getCustomTagWorker(IElementNode tag, ProcessorContext context) {
        if (tag.name().equals(PageMarginBoxContextNode.PAGE_MARGIN_BOX_TAG)) {
            return new PageMarginBoxImagesWorker(tag, context);
        }
        return super.getCustomTagWorker(tag, context);
    }
}

private static class PageMarginBoxImagesWorker extends PageMarginBoxWorker {
    public PageMarginBoxImagesWorker(IElementNode element, ProcessorContext context) {
        super(element, context);
    }

    @Override
    public boolean processTagChild(ITagWorker childTagWorker, ProcessorContext context) {
        if (childTagWorker.getElementResult() instanceof Image) {
            // Or set fixed dimensions via setWidth/setHeight
            ((Image) childTagWorker.getElementResult()).setAutoScale(true);
        }
        return super.processTagChild(childTagWorker, context);
    }
}

通过在ConverterProperties中指定PageMarginBoxImagesTagWorkerFactory来使用它:

HtmlConverter.convertToPdf(htmlSrc, pdfDocument, 
        new ConverterProperties()
                .setTagWorkerFactory(new PageMarginBoxImagesTagWorkerFactory()));