I developed a python code that converts HTML to PDF. For this, I convert HTML to Image and convert Image to PDF again. My code works well on my platform(windows) but does not work on MacOS.
from PIL import Image
from selenium.webdriver.chrome.options import Options
import time
from PIL import Image
import img2pdf
import os
import sys
arguments=sys.argv
FileUrl=arguments[1]
for path, currentDirectory, files in os.walk(FileUrl):
for file in files:
if file.endswith(".html"):
driver=webdriver.Chrome()
filepath=os.path.join(path, file)
imageoutputPath=filepath.replace('.html','_desktop.png')
pdfoutputPath=filepath.replace('.html','_desktop.pdf')
driver.get(filepath)
time.sleep(3)
height = driver.execute_script("return Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight )")
print(height)
driver.close()
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument(f"--window-size=700,{height}")
chrome_options.add_argument("--hide-scrollbars")
driver = webdriver.Chrome(options=chrome_options)
driver.get(filepath)
driver.save_screenshot(imageoutputPath)
image = Image.open(imageoutputPath)
pdf_bytes = img2pdf.convert(image.filename)
file = open(pdfoutputPath, "wb")
file.write(pdf_bytes)
image.close()
file.close()
print("Successfully made pdf file")
os.remove(imageoutputPath)
driver.close()
The 26 th line chrome_options.add_argument(f"--window-size=700,{height}") has syntax invalid error
Please let me know how to fix this problem
CodePudding user response:
I tried to run this code on my local. On windows, it works perfect. In Mac,
- you can change 26th line like below first.
chrome_options.add_argument("--window-size=700," f{height}")
- driver=webdriver.Chrome() might not work, I think. I recommend use chromedriver like this.
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver=webdriver.Chrome(service=Service(ChromeDriverManager().install()))
You can also use chromedriver like this. But I know, executable_path was deprecated.
driver=webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')
I am sure you installed all modules using pip3 install.
Hope this would be helpful.