4

嗨,我正在尝试将图像添加到我的 pdf 中。它正在被添加,但问题是我无法设置用户定义的宽度和高度。我正在使用XMLWorkerHelper转换 HTML 代码并将其写入 PDF。

try {
String image="<img alt=\"Not Loading\" src=\"C:\\Users\\sathesh_S\\Desktop\\Itext\\football.jpg\" style=\"width: 50px; height: 75px\" />";    
OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
InputStream is = new ByteArrayInputStream(image.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
file.close();
}
catch (Exception e) 
{
e.printStackTrace();
}

在这里,我将宽度和高度设置为 50 和 75 像素。但是原始图像被添加到 PDF 中。我该如何纠正这一点。

4

1 回答 1

4

XMLWorker 不支持图像 [1] 上的宽度和高度 css 属性。

默认图像标签处理器(即com.itextpdf.tool.xml.html.Image)使用标签的宽度/高度属性。所以有两种解决方案:

  1. 为图像编写自己的图像标签处理器(可能还有 CssAplier)(有关详细信息,请参阅库源代码),或者简单地:
  2. 使用 img 标签的 height 和 width 属性,例如:

    String image="<img src=\"football.jpg\" width=\"50px\" height=\"75px\"/>";
    

第二种解决方案要容易得多,在大多数情况下应该足够了。

[1] http://demo.itextsupport.com/xmlworker/itextdoc/CSS-conformance-list.htm

于 2013-11-15T12:48:01.833 回答