pdfkit 在转换时将 href 从相对路径更改为绝对路径

pdfkit changes href from relative to absolute paths on conversion

我正在使用 pdfkit 转换 html 个具有带 href 属性链接的文件。

在html里面,href是用相对路径写的,例如:

<a href="folder/picture.jpg">PIC</a>

当我将其转换为 pdf 时,href 似乎自动重写为绝对路径 (C:/Users/...)。

为什么pdf会改变href?

通常当您从 HTML 文件创建 PDF 时,PDF 文件将在另一个位置打开(例如,通过邮件发送后在另一台计算机上打开)。因此,为了正确引用,需要完整路径。

当然这只有在另一台计算机可以访问该路径的情况下才有效(因此如果该路径可以从另一台计算机访问)。对于 C 上的路径:这仅适用于本地主机,不适用于其他 PC。

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