简体   繁体   English

使用“边距:自动和显示块”将图像居中时出现问题,并使用FlyingSaucer(Itext5)从XHTML解析为PDF

[英]Problem centering an image with : “margin : auto and display block” and parsing from XHTML to PDF using FlyingSaucer (Itext5)

I'm trying to parse an xhtml with a centered image to PDF using FlyingSaucer. 我正在尝试使用FlyingSaucer将带有居中图像的xhtml解析为PDF。

The image is centered using css : 图像使用css居中:

 img.center {
    display: block;
    margin-bottom: 1px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 1px;
}

and is perfectly centered when displayed on a browser. 并且在浏览器上显示时居中。 codePen link codePen链接

Thing is, when I try to create a PDF using the same xhtml file and the FlyingSaucer Library : image is not longer centered. 问题是,当我尝试使用相同的xhtml文件和FlyingSaucer Library创建PDF时:图像不再居中。

 PDFRenderer.renderToPDF(htmlFile, "pdf_file.pdf");

pdf显示未居中图像

I've tryed a few different approach but none seem to be working fine. 我尝试了几种不同的方法,但似乎都无法正常工作。

The only approach that worked for me was adding a width attribute to the img. 对我有用的唯一方法是在img中添加width属性。

However, the xhtml is an input provided by a external web service and it can't be changed . 但是, xhtml是外部Web服务提供的输入,不能更改

Adding the width attribute post reception of the file is doable but very dirty (you can find the sample code in the github repository below) 在文件接收后添加width属性是可行的,但是很脏(您可以在下面的github存储库中找到示例代码)

Do you have an idea on how to display this image the same way in PDF than on a browser without changing the html or css ? 您是否有想法在不更改html或css的情况下以与浏览器相同的方式在PDF中显示此图像?

Source project 源项目

https://github.com/Shask/FlyingSaucerXHTMLToPdfBug https://github.com/Shask/FlyingSaucerXHTMLToPdfBug

PS : I'm happy to change parsing library, so Far I've tryed different version of FlyingSaucer (using Itext5 and the other using OpenPDF) PS:我很高兴更改解析库,因此到目前为止,我尝试了其他版本的FlyingSaucer(使用Itext5,另一个使用OpenPDF)

Some update : 一些更新:

As of yet, I've tried a few java libraries to do the job. 到目前为止,我已经尝试了一些Java库来完成这项工作。

It seems that only Itext7 can get a good result on a PDF out of the box. 看来,只有Itext7才能在PDF上立即获得良好的结果。

You can find detailed result on github . 您可以在github上找到详细的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM