xhtml2pdf为本地html文件生成空白pdf

问题描述

我有一个使用Bokeh生成的交互式html文件。我正在尝试使用xhtml2pdf将html文件转换为pdf,但是使用xhtml2pdf或pdfkit的html文件上的图像不会显示在pdf上。

我尝试使用PyQt生成pdf,但效果很好,但是在转换为可执行文件时有问题,并且pdfcrowd也可以工作,但它是一个付费库。我已经在网上查看了所有其他解决方案,但这些解决方案似乎都不起作用。

这是html文件生成:

    source = ColumnDataSource(data=dict(x=xx,y=yy,z=val))
    
    surface1 = Surface3d1(x="x",y="y",z="z",data_source=source,width=600,height=600)
    surface2 = Surface3d2(x="x",height=600)
    surface3 = Surface3d3(x="x",height=600)
    surface4 = Surface3d4(x="x",height=600)
    
    l1 = gridplot([[Div(text = 'Side View 1'),Div(text = 'Front View')],[surface1,surface2]])
    l2 = gridplot([[Div(text = 'Side View 2'),Div(text = 'Top View')],[surface3,surface4]])

    filename = filename_out.split("\\")
    
    layout = column(Div(text = str(filename[-1].replace('_',' '))),Div(text = 'Absolute Warpage = ' + str(warpage)),l1,l2)
    output_file(filename_out[:-1]+'.html',title = 'CMM Scan',mode = 'inline')
    save(layout)

这是转换为pdf的代码

def convert_html_to_pdf(source_html,output_filename):
from xhtml2pdf import pisa 
# open output file for writing (truncated binary)
result_file = open(output_filename,"w+b")

# convert HTML to PDF
pisa_status = pisa.CreatePDF(
        source_html,# the HTML to convert
        dest=result_file)           # file handle to recieve result

# close output file
result_file.close()                 # close output file

# return True on success and False on errors
return pisa_status.err

convert_html_to_pdf(str(filename_out+'.html'),str(filename_out+'.pdf'))

解决方法

标准散景图是渲染到HTML栅格画布的JavaScript程序。听到任何东西都可以隐藏到PDF中,我感到有些惊讶。当然,任何仅查看基本HTML内容却不实际执行JS代码的转换工具都行不通。 PyQt之所以很有用,是因为它嵌入了实际的真实浏览器引擎,而其他工具却没有。

在地块上设置output_backend="svg"可能会带来更好的运气(但请注意,Bokeh的SVG支持还解决了一些已知问题,因此YMMV)。但是,我怀疑这也可能会遇到上述相同的问题,其中运行JS代码是产生SVG的原因,而缺少JS引擎,则不会显示任何图。

最终,唯一的选择可能是将散景图单独导出(例如,使用export_svgsexport_png)到可以包含在PDF(或包含以下内容的HTML文档中)的静态PNG或SVG中:然后可以在不运行JS代码的情况下将其天真地转换为PDF。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...