【问题标题】:Why [tag:weasyprint] xhtml-to-pdf does not fit A4 page?为什么 [tag:weasyprint] xhtml-to-pdf 不适合 A4 页面?
【发布时间】:2020-01-19 21:31:22
【问题描述】:

我尝试使用 weasyprint Python 3 API 将“xhtml 网页”转换为“A4 肖像 pdf”。 Here 是页面。
但是最后的 pdf 文件不适合 A4 页面。
这是python代码:

#!/usr/bin/python3

from weasyprint import HTML, CSS
import subprocess

Page = HTML(url="https://educadhoc.hachette-livre.fr/extract/complet/9782401058705/show-page/page325.xhtml")
Style = CSS(string='''
    @page {
        size: A4 portrait;
        max-height:100%;
        max-width:100%;
        }
''')
Page.write_pdf(target="Try.pdf", zoom=1, stylesheets=[Style])
subprocess.Popen(["evince", "Try.pdf"])

即使在 CSS 样式中使用“尺寸 A4 肖像”和在 write_pdf 方法中使用“zoom=1”,它也不适合 A4!
(pdf文件中也有换行!...)
你有什么建议?

【问题讨论】:

  • 您找到解决方案了吗?我有类似的问题

标签: python pdf xhtml weasyprint


【解决方案1】:

是的! 我变了 ... 停止使用 Wea​​syprint 并使用 selenium,更可定制

#!/usr/bin/python3
# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


######  SELENIUM PARAMETERS
path_to_binary = "/usr/bin/firefox-esr"
path_to_webdriver = "/usr/local/bin/geckodriver"
capabilities = webdriver.DesiredCapabilities().FIREFOX
my_options = Options()
my_options.headless = True
my_options.add_argument("--width=1426")
my_options.add_argument("--height=2048")
my_options.binary_location = path_to_binary
my_service = Service(path_to_webdriver)


######  GO GO GO !
driver = webdriver.Firefox(service=my_service, options=my_options)
driver.get("https://educadhoc.hachette-livre.fr/extract/complet/9782401058705/show-page/page325.xhtml")
driver.execute_script("document.body.style.transform = 'scale(3)'")
driver.find_element_by_tag_name("body").screenshot("TRY.png")
driver.implicitly_wait(2)
driver.close()
  • 它就像一个魅力,但在 png 图像文件中(还不错);根据 Firefox 检查器,原始网页为 1426x2048。
  • 我在driver.execute_script 行中添加了一个scale(3),您可以根据自己的需要进行调整,以使图像尺寸和质量提高3 倍...(但重量提高3 倍!)
  • 您需要在正确的路径(在我的情况下为/usr/local/bin/geckodriver)安装一个 webdriver(在我的情况下是 firefox 的),并且您还必须找到二进制路径(在我的情况下为/usr/local/bin/firefox-esr)。
  • Firefox 的最后一个网络驱动程序(适用于 Linux、Mac 或 Win)可在以下位置下载:https://github.com/mozilla/geckodriver/releases
  • 然后,你可以用这个PNG文件做你想做的事! (例如,如果你愿意,可以使用imagemagick 转换成不同的格式,如pdf ...)Link to Convert

  • 希望对您和其他 Python 初学者有所帮助...

【讨论】:

  • 谢谢,我试试看!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 2014-08-22
  • 2017-10-08
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
  • 2018-12-23
相关资源
最近更新 更多