How to Save a File from a Website as PDF

How to save a .pdf from a browser?

From the errorneous response which appears to be just a HTML error page:

alert('Session timed out. Please login again.\n');

It thus appears that downloading the PDF file is required to take place in a valid HTTP session. The HTTP session is backed by a cookie. The HTTP session in turn contains in the server side usually information about the currenty active and/or logged-in user.

The Selenium web driver manages cookies all by itself fully transparently. You can obtain them programmatically as follows:

Set<Cookie> cookies = driver.manage().getCookies();

When manually fiddling with java.net.URL outside control of Selenium, you should be making sure yourself that the URL connection is using the same cookies (and thus also maintaining the same HTTP session). You can set cookies on the URL connection as follows:

URLConnection connection = new URL(driver.getCurrentUrl()).openConnection();

for (Cookie cookie : driver.manage().getCookies()) {
String cookieHeader = cookie.getName() + "=" + cookie.getValue();
connection.addRequestProperty("Cookie", cookieHeader);
}

InputStream input = connection.getInputStream(); // Write this to file.

How to save multiple web pages as pdf files or screenshot using excel macro?

You may save a webpage as PDF simply using headless Chrome via command line:

lRet = CreateObject("WScript.Shell").Run("""C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"" --headless --disable-gpu --print-to-pdf=""C:\Test\Sample.pdf"" https://api.myip.com", 1, True)
MsgBox "Ret code: " & lRet

You need to specify the actual path to your Chrome, and to the PDF file to be saved. Note, you need Chrome version 60 or higher to run the code on Windows.

How to save web page as PDF?

Here is the Swift code for converting webPage to image, then you can convert it to PDF:

    let sizevid = CGSizeMake(1024, 1100)

UIGraphicsBeginImageContext(sizevid);

webview.layer.renderInContext(UIGraphicsGetCurrentContext()!)

let viewImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

var imageData = NSData()

imageData = UIImagePNGRepresentation(viewImage)!

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

let pathFolder = String(String(format:"%@", "new.png"))

let defaultDBPathURL = NSURL(fileURLWithPath: documentsPath).URLByAppendingPathComponent(pathFolder)

let defaultDBPath = "\(defaultDBPathURL)"

imageData.writeToFile(defaultDBPath, atomically: true)

// After converting it in to an image you can easily convert it as pdf.


Related Topics



Leave a reply



Submit