【发布时间】:2018-07-25 09:25:50
【问题描述】:
我正在使用 pdfkit 来转换包含带有 href 属性的链接的 html 文件。
在 html 内部,href 是用相对路径编写的,例如:
<a href="folder/picture.jpg">PIC</a>
当我将其转换为 pdf 时,href 似乎会自动重写为绝对路径 (C:/Users/...)。
为什么pdf会改变href?
【问题讨论】:
标签: python wkhtmltopdf pdfkit
我正在使用 pdfkit 来转换包含带有 href 属性的链接的 html 文件。
在 html 内部,href 是用相对路径编写的,例如:
<a href="folder/picture.jpg">PIC</a>
当我将其转换为 pdf 时,href 似乎会自动重写为绝对路径 (C:/Users/...)。
为什么pdf会改变href?
【问题讨论】:
标签: python wkhtmltopdf pdfkit
pdfkit依赖的wkhtmltopdf默认将相对链接转换为绝对链接。
这可以通过使用带有特殊标志的命令行工具来停止:
wkhtmltopdf --keep-relative-links src destination
或者通过告诉 pdfkit 应用这个选项:
def convert_to_pdf(path):
try:
# run the conversion and write the result to a file
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
options = {
'--keep-relative-links': ''
}
pdfkit.from_url(path+'.htm', path+'.pdf', configuration=config, options=options)
except Exception as why:
# report the error
sys.stderr.write('Pdf Conversion Error: {}\n'.format(why))
raise
【讨论】:
通常,当您从 HTML 文件创建 PDF 时,PDF 文件将在另一个位置打开(例如,在通过邮件发送后在另一台计算机上打开)。因此,为了正确引用完整路径。
当然,这仅在另一台计算机可以访问该路径时才有效(因此,如果该路径可以从另一台计算机访问)。使用 C 上的路径:这仅适用于本地主机,而不适用于其他 PC。
【讨论】: