代码之家  ›  专栏  ›  技术社区  ›  David J.

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

  •  0
  • David J.  · 技术社区  · 6 年前

    我正在使用pdfkit来转换html文件,这些文件中有带有ref属性的链接。

    在html内部,使用相对路径编写href,例如:

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

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

    为什么pdf会更改href?

    2 回复  |  直到 6 年前
        1
  •  1
  •   David J.    6 年前

    默认情况下,pdfkit依赖的wkhtmltopfd将相对链接转换为绝对链接。

    这可以通过使用带有特殊标志的命令行工具来停止:

    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
    
        2
  •  0
  •   misanthrop    6 年前

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

    当然,只有当另一台计算机可以访问该路径(因此,如果可以从另一台计算机访问该路径)时,此操作才有效。对于C上的路径:这只能在本地主机上工作,而不能在其他pc上工作。