簡體   English   中英

為什么 [tag:weasyprint] xhtml-to-pdf 不適合 A4 頁面?

[英]Why [tag:weasyprint] xhtml-to-pdf does not fit A4 page?

我嘗試使用 weasyprint Python 3 API 將“xhtml web 頁面”轉換為“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 樣式中使用“尺寸 A4 肖像”和在 write_pdf 方法中使用“zoom=1”,它也不適合 A4!
(pdf 文件中也有換行......)
你有什么建議?

是的。 我改變了..,停止使用 Weasyprint 和 go 到硒,更可定制

#!/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 檢查員,原始 web 頁面為 1426x2048。
  • 我在driver.execute_script行中放置了一個scale(3) ,您可以根據自己的需要進行調整,以便獲得 3 倍高的圖像尺寸和質量......(但重 3 倍!)
  • 您需要在正確的路徑(在我的情況下是/usr/local/bin/geckodriver )中安裝 webdriver(在我的情況下是 firefox),並且您也必須找到二進制路徑( /usr/local/bin/firefox-esr在我的情況下)。
  • Firefox(對於 Linux、Mac 或 Win)的最后一個 webdriver 可在以下位置下載: https://github.com/mozilla/geckodriver
  • 然后,你可以用這個 PNG 文件做你想做的事。 (例如,如果需要,請使用imagemagick轉換為 pdf 等不同格式...)鏈接到轉換

  • 希望它可以幫助您和其他 Python 初學者...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM