from selenium import webdriver from selenium.webdriver.chrome.options import Options import time import os import base64 # Configure Chrome to save PDFs automatically chrome_options = Options() download_dir = os.path.join(os.getcwd(), "invoices") os.makedirs(download_dir, exist_ok=True) prefs = { "printing.print_preview_sticky_settings.appState": '{"recentDestinations":[{"id":"Save as PDF","origin":"local","account":""}],"selectedDestinationId":"Save as PDF","version":2}', "savefile.default_directory": download_dir, "download.default_directory": download_dir, "download.prompt_for_download": False, "plugins.always_open_pdf_externally": True } chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(options=chrome_options) driver.get("https://www.amazon.com/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2F%3Fref_%3Dnav_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=usflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0") # Wait for manual login input("Log in and press Enter...") with open("orders.txt") as f: orders = [line.strip() for line in f] for order in orders: url = f"https://www.amazon.com/gp/css/summary/print.html?orderID={order}&ref_=ppx_hzod_invoiceConns_dt_b_invoice" driver.get(url) time.sleep(3) # Save as PDF with order ID as filename print_options = { 'landscape': False, 'displayHeaderFooter': False, 'printBackground': True, 'preferCSSPageSize': True, } result = driver.execute_cdp_cmd("Page.printToPDF", print_options) # Save the PDF pdf_path = os.path.join(download_dir, f"{order}.pdf") with open(pdf_path, 'wb') as f: f.write(base64.b64decode(result['data'])) print(f"Saved: {order}.pdf")