How to print PDF landscape with selenium python
Asked Answered
C

2

8

I've been succeeding to print and download pdf with my script above, but I have a problem how to print/download pdf with selenium python in a LANDSCAPE mode output.

I try to used pdfkit with "fromstring" with selenium "driver.getsource" but the portrait mode not so good result and finally I choose to use print PDF from chromedriver and I've succeeded make a PDF file that I want with good result but stuck in only portrait mode. Even though what I need is in landscape mode

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select

import time
import pdfkit
import json
import os

curr_dir = os.getcwd()
download_path = os.path.join(curr_dir, 'dl')
appState = {
    "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local"
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "version": 2,
}

profile = {
    'printing.print_preview_sticky_settings.appState': json.dumps(appState),
    'savefile.default_directory': download_path,
}

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome("D:\\master\\chromedriver\\2.45\\chromedriver.exe", 
chrome_options=chrome_options)
URL = "taget site"


def site_login():
    driver.get(URL)
    driver.find_element_by_id('username').send_keys('username')
    driver.find_element_by_id ('password').send_keys('pass')
    driver.find_element_by_name('login').click()

def get_abc():
    driver.get('https://targetsite/abc')
    driver.find_element_by_name('year_id_combo')
    s1 = Select(driver.find_element_by_name('year_id_combo'))
    s1.select_by_visible_text('summer')

    select_box = driver.find_element_by_name('course_id')

    mk = [x for x in select_box.find_elements_by_tag_name("option")]

    course_name = mk[2].text
    course_name = course_name.replace(' ', '_')

    index_mk = course_name.index('|')
    course_name = course_name[:index_mk]

    s2 = Select(driver.find_element_by_name('course_id'))
    s2.select_by_value(mk[2].get_attribute('value'))

    s3 = Select(driver.find_element_by_name('class'))

    list_class = driver.find_element_by_name('class')
    class = [x for x in list_class.find_elements_by_tag_name("option")]

    s3.select_by_value(class[1].get_attribute('value'))

    # multiple windows handle
    main_window_handle = None
    while not main_window_handle:
        main_window_handle = driver.current_window_handle

    driver.find_element_by_xpath( '/html/body/div[3]/div[2]/div/div/div[1]/div[1]/div/div[2]/div[2]/div/input[1]').click()
    print_window_handle = None
    while not print_window_handle:
        for handle in driver.window_handles:
            if handle != main_window_handle:
               print_window_handle = handle
               break

    driver.switch_to.window(print_window_handle)
    webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()

    driver.execute_script(
        "document.title='{}';window.print();".format(course_name)
    )

def logout_system():
    driver.find_element_by_xpath('//a[normalize- 
    space(text())="Logout"]').click()


def close():
    driver.close()
    driver.quit()


site_login()
time.sleep(5)
get_abc()
time.sleep(70)
logout_system()
time.sleep(5)
close()

I Expect the result printed in pdf landscape mode, but I don't know how to make it landscape with this situation, the result now is only a portrait PDF.

Care answered 7/1, 2019 at 12:15 Comment(0)
U
3

Not sure if this is still needed, but you can add ""isLandscapeEnabled": True," to the appState:

appState = {
    "recentDestinations": [{"id": "Save as PDF", "origin": "local"}],
    "selectedDestinationId": "Save as PDF",
    "version": 2,
    "isLandscapeEnabled": True}
Upshot answered 21/9, 2021 at 19:20 Comment(0)
S
1

You can use a combination of selneium's keyboard actionkeys and python's "PyUserInput" package to automate keystrokes independently of selenium.

So with Selenium you can use the combination of "CTRL + P" if you are using Windows.

Then from either Selnium or or "pykeyboard" which is under PyUserInput, you can you automate the process of keystrokes for "Tabbbing" until you see the Portrait vs Landscape dropdown.

You can then use the arrow keys in either and then hit use those automated keystrokes to hit the "Enter" or the "Return" key to save as Landscape.

Seato answered 18/12, 2019 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.