I have been asked to do kind of a special thing the other day:
Stéphane, do you know if we can print a webpage in PDF with powershell, so we can archive the look and feel of our web application?
Well, right now, I don’t know how to print a webpage in PDF with powershell. But give a few minutes, and I’ll code you something.
In other words, I was asked to export webpages to pdf using powershell. Doens’t sound that difficult doesn’t it?
Like every project, I always start by googling. Very often we can find a script to start with, or at least something that will guide us in the right direction to go.
I noticed very quickly that to have the same output as the webpage, we needed to print it directly from Internet Explorer. Also, to export the page as showed in the browser, PDFCreator seemed like the best choice to me. With these basic ideas in mind, I started my google fu.
The first resultats I got was a Script on technet, that would modify some specefic registry values of the PDFCreator settings, and then print a document out. (available here)
I actually never got that method to work. I tried defining a Print Profile and specefiying that one for my print job, but that never worked out well me (Especially since PDFForge made a complete change in the latest version of their product, and shifted quite a few things in their registry hyve. After a while, I gave it up, and searched through the documention of PDFCreator. Not much to get me started there either. BUT I did found a folder with script ‘samples’ though!
As usual, there are no PowerShell examples, BUT, I found 4 vbs script samples, which were perfect to get me start.
The main thing that the VBS scripts were doing is creating an instance of the PDFCreator.JobQueue comobject. This was a great start, and it led my way to the final function that you can find at the end of this post.
Main points I would like to highlight about this function:
Some important information:
- PDFCreator version 2.3.2 together with –>
- PowerShell version 3.0
- PowerShell version 4.0
- PowerShell version 5.0
We also tried this function on Windows Server 2008 R2 (which had PowerShell V2). For some reason, we couldn’t fully install the PDFCreator. The installer needs to have access to the internet to download some additional files, which it couldn’t do since it was blocked by our Proxy.
I then had the error message: “Could not find the method ‘Initialize'” when I launched the function. The com instance simply was missing a method.
So it is still unclear why it didn’t work on the Windows 2008 server; either because PowerShell version 3.0 is the minimum required version needed to make it work, or because of the additional files that could not be downloaded during the install. I asked on the PDFCreator forum right here. I’ll update this post as soon as I have an answer.