Friday, June 12, 2009

Powershell script for converting Word documents to PDF format

In my job, we only send documents to clients in pdf formats. Sometimes we have to send several documents at once and it takes a good time to open each one and save it as a pdf, it’s not a very pleasant task.

In order to minimize this problem, I’ve created a simple powershell script that opens a Word document and saves it as pdf without any user interaction. With such script, I can convert a lot of files at once, just like this:

ls . *.doc* –Recurse | %{ ~\scripts\doc2ps1.ps1 $_.fullname }

With this command, I list recursively each doc/docx file in a directory and save each one as PDF.

By default, Office 2007 apps are not able to save files as PDF, so you have to install the add-in from Microsoft first to use the script. The add-in is available here.

Bellow is the script, it’s also available in my PowerShell scripts repository at GitHub (http://github.com/dougfernando/utility-scripts/tree/master) as doc2pdf.ps1.

param (
[string]$source = $(Throw "You have to specify a source path."))

$extensionSize = 3
if ($source.EndsWith("docx")) {
$extensionSize = 4
}

$destiny = $source.Substring(0, $source.Length - $extensionSize) + "pdf"
$saveaspath = [ref] $destiny
$formatPDF = [ref] 17

$word = new-object -ComObject "word.application"
$doc = $word.documents.open($source)
$doc.SaveAs($saveaspath, $formatPDF)
$doc.Close()

echo "Converted file: $source"

ps winword | kill

An important note, the script closes every Word instance in the end, so save any work previous using it.

97 comments:

Anonymous said...

Hello

your script is great . At the moment I need to convert docx files to word97-2003 format and was just wondering how you worked out that pdf format is [ref] 17?

thanks

Dermot

Anonymous said...

Damn, truly great topic. How will I find your subscription?

Kate Watcerson
bug finders

Steve B. said...

Hi,

Why did you kill the word processes at the end ?

Anonymous said...

I'll try to explain why it is 17 and not 18 or whatever.
If you look at the Document.SaveAs Method http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas(v=vs.80).aspx, you'll notice that its attribute are passed by reference. Here we need the FileFormat. Going to the description of the WdSaveFormat Enumeration http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.wdsaveformat.aspx , we notice that the wdFormatPDF, an enumberation member responsible for saving to PDF, has a number 0f 17 (I don't know why the Member table does not have a column with numbers, I think the leftmost column was supposed to have these numbers but eventually was published empty).

Raju said...

PDF => 17
Other numberers can be discovered
using .net reflector on Microsoft.Office.Interop.Word.dll and searching for wdsaveformat

Anonymous said...

Thanks... very helpful.
There's a little error in my env.
line 15,no ref.

Mohan said...

Hi,

I am not able to convert RTF files greater than 160MB, it throws up the following exception, even though other RTF's in the same folder converts just fine.

Exception calling "SaveAs" with "2" argument(s): "Command failed"
At C:\test\rtf2pdf.ps1:15 char:1
+ $doc.SaveAs($saveaspath, $formatPDF)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : COMException

Sometimes it says it converted sucessfuuly but i am not able to locate the PDF.

Converted file: C:\source\huge\RTFtable-lisitng-Huge.rtf

Anonymous said...

Superb, what a blog it is! This blog provides useful data to
us, keep it up.

my page; http://www.grupogedai.com.br/content/ways-create-pr-release

Anonymous said...

Nice post. I learn something totally new and challenging on websites I stumbleupon every day.
It will always be interesting to read through articles from other
writers and practice something from their sites.


Here is my website: manufacturing information

Anonymous said...

Hello to every body, it's my first pay a visit of this web site; this blog consists of remarkable and truly excellent material for readers.

Look into my web-site; publishing news

Anonymous said...

Good article. I certainly love this site. Stick with it!


Also visit my page ... finance article

Anonymous said...

I blog quite often and I seriously appreciate your content.
The article has truly peaked my interest. I'm going to book mark your website and keep checking for new information about once per week. I subscribed to your Feed too.

Here is my homepage; 50.co.za

Anonymous said...

What's up Dear, are you in fact visiting this web page on a regular basis, if so after that you will definitely obtain pleasant experience.

Also visit my weblog ... Motorcycle Articles

Anonymous said...

If you would like to increase your knowledge only keep visiting this web page and be updated with the most
recent news update posted here.

Feel free to visit my website http://www.boersenkreis-halle.de/wiki/index.php?title=Methods_to_promote_your_small_business_with_press_announcements

Anonymous said...

I blog frequently and I genuinely thank you for your content.
Your article has really peaked my interest.
I'm going to bookmark your blog and keep checking for new information about once per week. I subscribed to your RSS feed as well.

Here is my webpage; Public Relations

Anonymous said...

What's up all, here every person is sharing these knowledge, therefore it's
fastidious to read this weblog, and I used to visit this website everyday.


Here is my weblog; clubitaliani.com

Anonymous said...

Hey there! Are you aware should they make any plugins to assist
with SEO? I’m looking to get my blog to rank in te se's for some targeted keywords but I’m perhaps not seeing excellent gains. Once you learn of any please share. Be thankful!

my homepage: public relation

Anonymous said...

As the admin of this web page is working, no uncertainty very soon it
will be famous, due to its quality contents.

Feel free to visit my webpage; Real Estate News

Anonymous said...

Right here is the perfect website for anybody who hopes
to find out about this topic. You understand a whole lot its almost tough to argue
with you (not that I actually will need to…HaHa).
You certainly put a brand new spin on a topic that's been discussed for decades. Great stuff, just excellent!

Also visit my page financial business news

Anonymous said...

I don't know whether it's just me or if perhaps everybody else encountering problems
with your site. It appears as if some of the written text within your content
are running off the screen. Can someone else please provide feedback and
let me know if this is happening to them as well?
This could be a issue with my web browser because I've had this happen before. Thanks

Feel free to surf to my site; art on Line

Anonymous said...

When I originally left a comment I seem to have clicked on the -Notify
me when new comments are added- checkbox and now whenever a comment
is added I recieve four emails with the exact same comment.
There has to be a means you can remove me from that service?
Thank you!

Have a look at my website: auto news

Anonymous said...

Hello would you mind stating which blog platform you're using? I'm going to start my own blog soon but
I'm having a tough time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something completely unique.

P.S Sorry for being off-topic but I had to ask!


My site: icsci.it

Anonymous said...

Hi I am so happy I found your web site, I really found you by error, while I was searching on Digg for something else, Regardless I am here now and would just
like to say thanks for a incredible post and a all round enjoyable blog (I
also love the theme/design), I don’t have time to read it all at the
minute but I have saved it and also added your RSS feeds,
so when I have time I will be back to read much more, Please
do keep up the excellent jo.

Feel free to visit my page rv news

Anonymous said...

There’s a lot of folks that I do believe would enjoy your content.
Please allow me to know. Thank you

Here is my blog; communications and public relations

Anonymous said...

I hardly write remarks, but i did some searching and wound up here "Powershell script for converting Word documents to PDF format".

And I actually do have a couple of questions for you if
it's allright. Is it only me or does it give the impression like some of the responses look like left by brain dead people? :-P And, if you are posting on additional social sites, I would like to keep up with everything fresh you have to post. Could you make a list of the complete urls of all your shared sites like your linkedin profile, Facebook page or twitter feed?

Here is my blog post :: design communication

Anonymous said...

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now
each time a comment is added I get four emails with the same comment.
Is there any way you can remove people from that service?
Bless you!

Here is my blog - restaurant news

Anonymous said...

It's an awesome post designed for all the web people; they will get advantage from it I am sure.

Here is my web page http://social.kurdadv.com/

Anonymous said...

Magnificent goods from you, man. I've understand your stuff previous to and you're just too magnificent.
I really like what you have acquired here, certainly like what you're stating and the way in which you say it. You make it enjoyable and you still take care of to keep it sensible. I can't wait to read much more from you.
This is actually a wonderful website.

My website; fashion dress

Anonymous said...

Article writing is also a excitement, if you be acquainted with after that you
can write or else it is complicated to write.

Also visit my web page Direct Marketing News

Anonymous said...

I was wondering should anyone ever considered
changing the structure of your web log? Its very well written; I really like what youve got to say.
But perchance you could a little more when
it comes to content so people could relate to it better.
Youve got a lot of text for only having one or 2 pictures.
Perhaps you could space it out better?

Feel free to surf to my homepage - educational articles

Anonymous said...

Hi there Dear, are you truly visiting this web page
regularly, if so afterward you will without doubt take pleasant know-how.



Take a look at my blog http://Article-Crash.info

Anonymous said...

Good day! I know that is kinda off topic however I’d figured I’d ask.

Would you be interested in trading links or even guest authoring a blog post or vice-versa?
My site explains a lot of the same topics as yours and I believe we're able to greatly reap the benefits of each other. If you be interested feel free to shoot me a contact. I look forward to hearing from you! Fantastic web log in addition!

Review my web page - news environment

Anonymous said...

I think that everything composed was actually very reasonable.
But, think on this, suppose you added a little information?
I ain't suggesting your information isn't solid., however suppose you added something that
grabbed folk's attention? I mean "Powershell script for converting Word documents to PDF format" is kinda vanilla. You might peek at Yahoo's front page and note
how they create article titles to get viewers to open the links.
You might try adding a video or a pic or two to grab readers interested about what you've got to say. In my opinion, it might make your posts a little bit more interesting.

Also visit my web-site Fashion Women

Anonymous said...

I loved as much as you will receive carried out right here.
The sketch is attractive, your authored subject
matter stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following.
unwell unquestionably come more formerly again since exactly
the same nearly very often inside case you shield this hike.


my website communications print

Anonymous said...

I am curious to find out what blog system you are utilizing?

I'm having some small security issues with my latest blog and I'd like to find something more safe.
Do you have any solutions?

my weblog; http://Mtp.me

Anonymous said...

whoah this weblog is excellent i like reading your posts. Keep
up the great work! You know, lots of people are hunting around for this information, you could aid them greatly.


My web site: Video Games News

Anonymous said...

Plz reply as I’m trying to design my own, personal web log and would like to know where u got this from.

thanks

my webpage: lifestyle fashion

Anonymous said...

Way cool! Some extremely valid points! I appreciate you writing this write-up plus the
rest of the website is also really good.

Visit my web blog; energy pr

Anonymous said...

I enjoy reading through an article that can make people think.
Also, thanks for allowing for me to comment!

my webpage ... restaurant news

Anonymous said...

Plz reply as I’m trying to design my very own web log and want to know where u got this from.
thanks

Here is my homepage - recreational vehicle

Anonymous said...

I was suggested this website by my cousin. I'm not sure whether this post is written by him as nobody else know such detailed about my problem. You are wonderful! Thanks!

my web-site latest entertainment news

Anonymous said...

Thanks for the auspicious writeup. It in truth was once a leisure account it.

Glance complex to far brought agreeable from
you! By the way, how could we keep in touch?


Visit my blog post http://acsocial.com/index.php?do=/blog/22788/the-way-to-quit-mental-eating

Anonymous said...

I couldn't refrain from commenting. Very well written!

my webpage: electronic publishing

Anonymous said...

I am really loving the theme/design of one's weblog. Do you run into any internet browser compatibility problems? A number of my blog audience have complained about my site no longer working precisely in Explorer but looks great in Chrome. Are you experiencing any suggestions to greatly help fix this dilemma?

Have a look at my site :: college Universities

Anonymous said...

I'm truly enjoying the design and layout of your blog. It's a
very easy on the eyes which makes it much more pleasant for me to come here and visit more often.
Did you hire out a designer to create your theme? Fantastic work!


my web blog; College vs university

Anonymous said...

It's really very difficult in this busy life to listen news on TV, thus I just use world wide web for that purpose, and get the hottest news.

Also visit my blog :: rv news

Anonymous said...

My coder is wanting to persuade me to move to. net from PHP.
I've always disliked the theory because of the expenses. But he’s tryiong nevertheless. I’ve been using WordPress on numerous websites for around a year and am nervous about switching to a different platform. I've heard
very good things about blogengine. net. Is there a means I will transfer all my wordpress
content involved with it? Any help would be greatly appreciated!


Here is my webpage; women dating

Anonymous said...

That is a very good tip especially to those fresh to the blogosphere.
Simple but very precise info… Appreciate your sharing this one.
A must read article!

my homepage: story book

Anonymous said...

I feel this is among the most vital information for me.
And i am glad reading your article. But should commentary on some normal issues, The site
style is wonderful, the articles is in reality excellent : D.
Good process, cheers

Feel free to surf to my webpage :: marketing And advertising

Anonymous said...

It's very easy to find out any topic on net as compared to books, as I found this post at this web site.

Stop by my blog; real estate information

Anonymous said...

It's amazing to pay a visit this website and reading the views of all colleagues regarding this piece of writing, while I am also eager of getting know-how.

Have a look at my blog post ... http://community.urbansocietyd2r.com/groups/how-society-can-be-different-if-doctor-martin-luther-full-junior-was-still-in-existence/

Anonymous said...

Excellent job. I must say i enjoyed what you had to state, and more than that, how you presented it.
Too cool!

My weblog :: latest financial news

Anonymous said...

Hi would you mind letting me know which web host you're working with? I've loaded your blog in 3 completely different browsers and I
must say this blog loads a lot faster then most. Can you recommend a good internet hosting provider at a honest price?
Cheers, I appreciate it!

Look into my web page ... college university

Anonymous said...

Howdy could you mind letting me know which hosting company you’re
using? I’ve loaded your site in 3 different browsers and I have to say this blog loads much faster then
most. Is it possible to suggest a good hosting
provider at an acceptable price? Thanks, I appreciate it!


Also visit my site - news on environmental issues

Anonymous said...

Hi everyone, it's my first visit at this web page, and article is in fact fruitful for me, keep up posting such articles or reviews.

Also visit my web blog - classic car

Anonymous said...

My partner and I absolutely love your site and find
many your post’s to be what specifically I’m looking
for. is it possible to offer guest writers to create content for
you personally? I wouldn’t mind creating
a post or elaborating on some of the subjects you write with regards to here.
Again, awesome web log!

Feel free to surf to my site :: real estate market news

Anonymous said...

Hi there! Would you mind if I share your blog with my twitter group?

There's a lot of folks that I think would really appreciate your content. Please let me know. Many thanks

Feel free to surf to my blog post; real estate market news

Anonymous said...

I'm really enjoying the theme/design of your web site. Do you ever run into any browser compatibility issues? A few of my blog audience have complained about my blog not working correctly in Explorer but looks great in Chrome. Do you have any ideas to help fix this issue?

Here is my site - public relations news

Anonymous said...

Hello! I know this is sort of off-topic however I needed to ask.
Does managing a well-established blog such as yours take a massive
amount work? I am brand new to blogging but I do write in
my diary daily. I'd like to start a blog so I will be able to share my experience and thoughts online. Please let me know if you have any kind of ideas or tips for new aspiring blog owners. Thankyou!

Also visit my webpage - latest financial news

Anonymous said...

Just want to say your article is as astonishing. The clearness for your post is simply cool
and that i could think you are an expert on this subject.
Fine along with your permission allow me to clutch your feed
to keep updated with impending post. Thanks a million and please keep up the gratifying work.


my web site - arts theatre

Anonymous said...

Great blog you have here but I was wondering if you knew of any forums that cover the same topics discussed in this article?
I'd really like to be a part of group where I can get advice from other knowledgeable individuals that share the same interest. If you have any recommendations, please let me know. Cheers!

My homepage government articles

Anonymous said...

Hi there! Can you use Twitter? I’d like to follow you if that would be
ok. I’m absolutely enjoying your site and appearance forward to new updates.


my weblog In Direct Marketing

Anonymous said...

Hey would you mind stating which blog platform you're working with? I'm going to start my own blog in the near future but
I'm having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something completely unique.
P.S Apologies for getting off-topic but I had to ask!


Feel free to visit my homepage: financial article

Anonymous said...

Hello, this weekend is pleasant designed for me, as
this point in time i am reading this enormous informative post here at my
home.

Also visit my webpage ... azejus.com

Anonymous said...

Unquestionably believe that which you stated.

Your favorite justification appeared to be on the web the
easiest thing to be aware of. I say to you, I definitely get irked while people think about worries
that they plainly do not know about. You managed to hit
the nail upon the top and defined out the
whole thing without having side effect , people can take a
signal. Will likely be back to get more. Thanks

Also visit my web-site ... solar energy articles

Anonymous said...

It's not my first time to pay a quick visit this site, i am browsing this site dailly and take pleasant data from here every day.

Also visit my web-site :: news real estate

Anonymous said...

Can you mind if I quote a couple of your posts as long as I provide credit and sources back again to your website?
My internet site is in the same specialized niche as yours
and my users would certainly reap the benefits of a number of the information you present here.
Please allow me to know if this okay with you. Thanks a whole lot!



My website :: Solar Energy News

Anonymous said...

I do trust all the ideas you've offered to your post. They're really convincing and will certainly work.
Nonetheless, the posts are very quick for novices. May just you please extend them a little from next time?
Thank you for the post.

My homepage lifestyle travel

Anonymous said...

I suppose for the present time i’ll accept book-marking and adding your RSS feed
to my Google account. I enjoy brand new updates and will share this
website with my Facebook group. Chat soon!

Feel free to visit my web blog:

Anonymous said...

Hey are utilizing WordPress for your weblog platform? I’m a new comer to the blog world but I’m trying to get started and create
my very own. Would you require any html coding expertise to produce your
personal weblog? Any help could be greatly appreciated!


Look into my web-site :: Www.Miraslow.Com

Anonymous said...

It is not my first time to pay a visit this site, i am visiting this
website dailly and obtain good facts from here all the time.



Also visit my webpage: financial articles

Anonymous said...

These are in fact wonderful ideas in concerning blogging.
You have touched some nice things here. Any way keep up wrinting.


Take a look at my website: http://brain.kaist.ac.kr/wiki/index.php/%EC%82%AC%EC%9A%A9%EC%9E%90:DonaldCol

Anonymous said...

My partner and I stumbled over here from the different page and thought I may as well always check things out.

I like what I see so now i'm following you. Look forward to going over your on line page over and over repeatedly.

Take a look at my web blog sizkviz.wirenet.info

Anonymous said...

Thanks for a marvelous posting! I really enjoyed reading it, you're a great author.I will ensure that I bookmark your blog and will eventually come back in the future. I want to encourage yourself to continue your great work, have a nice holiday weekend!

Also visit my web page; socialtime.uv.ro

Anonymous said...

I do not know whether it's just me or if everyone else encountering problems with your site. It appears like some of the text on your posts are running off the screen. Can someone else please comment and let me know if this is happening to them too? This might be a issue with my browser because I've had this happen before.
Many thanks

My web blog; business and financial news

Anonymous said...

Thanks for the marvelous posting! I certainly enjoyed reading it, you can be
a great author. I will ensure that I bookmark your blog and will
often come back from now on. I want to encourage you continue your great posts,
have a nice weekend!

my website :: austriasocialnetworks.promotion.pk

Anonymous said...

Woah! I'm really digging the template/theme of this website. It's simple, yet effective.
A lot of times it's tough to get that "perfect balance" between user friendliness and visual appeal. I must say you have done a very good job with this. In addition, the blog loads extremely quick for me on Safari. Outstanding Blog!

My blog :: news free games

Anonymous said...

I believe everything composed made a ton of sense.
But, think about this, what if you were to write a killer title?

I am not saying your information is not solid., however what if you added a post title
that grabbed folk's attention? I mean "Powershell script for converting Word documents to PDF format" is kinda plain. You could peek at Yahoo's home page and watch how they create news headlines
to get viewers interested. You might try adding a video or a picture or
two to grab readers excited about everything've written. In my opinion, it would make your posts a little livelier.

my homepage: facemasre.com

Anonymous said...

Hello mates, nice post and nice urging commented here, I am in fact
enjoying by these.

Feel free to surf to my website ...

Anonymous said...

Simply wish to say your article is as surprising.
The clearness in your post is simply excellent and
i could assume you're an expert on this subject. Well with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please continue the gratifying work.

my weblog ... diamondteambuild.com

Anonymous said...

Pretty great post. I simply stumbled upon your weblog and wanted
to mention that I have really loved browsing your blog
posts. In any case I will be subscribing to your feed and
I hope you write again soon!

Review my webpage; mining manufacturing

Anonymous said...

Do you have a spam problem on this website; I also am a blogger, and I was wondering your position;
we now have created some nice methods and we're looking to trade strategies with others, please shoot me an email if interested.

my weblog art contest

Anonymous said...

This design is steller! You most definitely understand how to
keep a reader entertained. Betwixt your wit and your videos, I was almostmoved to start my own weblog (well,
very nearly... HaHa)

my web page ... home and family

Anonymous said...

Very nice post. I just stumbled upon your blog and
wanted to say that I have truly enjoyed browsing your blog
posts. After all I'll be subscribing to your feed and I hope you write again soon!

My homepage latest real estate news

Anonymous said...

Good post however I was wondering if you could write a litte more on this topic?
I'd be very thankful if you could elaborate a little bit further. Appreciate it!

my homepage ... recent food news

Anonymous said...

Hey! Quick question that’s totally off topic.
Are you aware how to make your site mobile friendly?
My web site looks weird when browsing from my iphone.
I’m searching for a template or plugin
that could be in a position to fix this dilemma. If you have any suggestions, please share.

Many thanks!

my web page :: financial news

Anonymous said...

That is very fascinating, You are an overly skilled blogger.
I've joined your rss feed and sit up for in search of extra of your wonderful post. Additionally, I've shared your website in my
social networks

Feel free to visit my web page; auto news

Anonymous said...

Oh my goodness! Impressive article dude! Many thanks, However I am having troubles with your
RSS. I don't know the reason why I can't join it.
Is there anybody getting similar RSS issues? Anyone who knows the answer can you kindly respond?

Thanx!!

Also visit my website art of photography

Anonymous said...

Hi, after reading this amazing article i am
also cheerful to share my knowledge here with
mates.

My blog ... Boots Makeup

Anonymous said...

you're truly a excellent webmaster. The site loading speed is incredible. It sort of feels that you're
doing any distinctive trick. In addition, The contents
are masterpiece. you've performed a wonderful task on this topic!

my web page - Interior Design New York City

Anonymous said...

Remarkable things here. I am very happy to see your post.
Thanks so much and I'm having a look ahead to contact you. Will you kindly drop me a e-mail?

Feel free to surf to my homepage: Ashley Furniture ()

Anonymous said...

This website was... how do I say it? Relevant!! Finally I've found something which helped me. Many thanks!

Also visit my page - furniture packages ()

Anonymous said...

Thank you for the good writeup. It in fact was once
a enjoyment account it. Glance complicated to more brought agreeable from you!
However, how can we keep up a correspondence?


my homepage ... just click the following article

Anonymous said...

I like the data you present here and can’t
wait to have a look when I go back home. I’m
surprised at how fast your blog loaded on my mobile phone.
I’m not using WIFI, just 3G. Anyhow, fantastic site!

My webpage :: New Business

Anonymous said...

Hi there everybody, here every person is sharing
these knowledge, therefore it's pleasant to read this web site, and I used to pay a quick visit this web site daily.

Here is my webpage ... Simply Click The Next Internet Page

Anonymous said...

Because the admin of this site is working, no doubt very quickly it
will be well-known, due to its quality contents.

My site :: Nightclub Design Is important For the Club's Recognition

Anonymous said...

The main things you need to have a hard time telling them apart.
As the cells regenerate they will replace the existing scar tissue
by new skin cells therefore cut down the appearance of stretch marks?
I tried everything that I could rely on and use to your stretch
mark problem.

My webpage; Read More At this website