我试图用weasyprint Python 3 API将一个 "xhtml网页 "转换成 "A4纵向pdf"。在这里,我尝试着将 "xhtml网页 "转换为 "A4人像pdf"。 是页面。但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样式中使用 "size A4 portrait",在write_pdf方法中使用 "zoom=1",它也不适合A4纸!(pdf文件中也有行数偏移!...)有什么建议?(在pdf文件中也有行的变化!...)你有什么建议?
是的!我改变了......停止使用Weasyprint,去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()
scale(3)
你可以根据你的需要在 driver.execute_script
为了有一个3倍以上的高图像尺寸和质量......。(但3倍更重!)/usr/local/bin/geckodriver
(在我的例子中),而且你还必须找到二进制路径(/usr/local/bin/firefox-esr
在我的例子中)。)然后,你可以对这个PNG文件做你想做的事情! (例如,使用 imagemagick
转换为不同的格式,如PDF,如果你想...) 链接到转换
希望它能帮助你和其他Python初学者... ...