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

时间:2018-07-25 09:25:50

标签: python wkhtmltopdf pdfkit

我正在使用pdfkit转换其中包含具有href属性链接的html文件。

在html内,href带有相对路径,例如:

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

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

为什么pdf会更改href?

2 个答案:

答案 0 :(得分:0)

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

当然,这仅在另一台计算机可以访问该路径时才有效(因此,如果可以从另一台计算机访问该路径)。在C上具有路径:仅在本地主机上有效,而在其他PC上无效。

答案 1 :(得分:0)

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