Sharepoint word to pdf

Most of you whom are searching around on this are aware of the solution for SharePoint 2010 (https://msdn.microsoft.com/en-us/library/office/ff181518(v=office.14).aspx). And chances are after you tried on your own to do this for 2013 that there was no List Definition type in VS, right? So after finding this (https://camerondwyer.wordpress.com/2013/09/20/how-to-create-a-custom-sharepoint-list-definition-using-visual-studio-2012/) I decided to frankenstein the old methods with the updated way to do it in Visual Studio. The results of the successful experiment are below.

Code It

This article describes the following steps to show how to call the Word Automation Services to convert a document:

  1. Creating a SharePoint 2013 Empty Project and Adding the SharePoint list.
  2. Adding a reference to the Microsoft.Office.Word.Server assembly.
  3. Adding an event receiver.
  4. Adding the sample code to the solution.

Creating a SharePoint 2013 List Definition (sort of) Application in Visual Studio 2012

This article uses a SharePoint 2013 list definition application for the sample code.

To create a SharePoint 2013 list definition application in Visual Studio 2012

  1. Start Microsoft Visual Studio 2012 as an administrator.
  2. In Visual Studio 2012 select File | New Project
  3. Select Templates | Visual C# | Office/SharePoint | SharePoint 2013 – Empty Project, Provide a name and location for the project/solution and OKcapture1-vsprojectName the project and solution something meaningful (ConvertWordToPDF perhaps?).

    To create the solution, click OK.

  4. Select a site to use for debugging and deployment.
  5. Select the site to use for debugging and the trust level for the SharePoint solution.
    Note
    Make sure to select the trust level Deploy as a farm solution. If you deploy as a sandboxed solution, it does not work because the solution uses the Microsoft.Office.Word.Server assembly. This assembly does not allow for calls from partially trusted callers.
  6. To finish creating the solution, click Finish.
  7. Once the new solution has been created, we can use the new Visual Designer to create the List Definition. Right click the project in the solution explorer and select Add | New Item
  8. Select Visual C# Items | Office/SharePoint | List, provide a name and click OK
  9. Provide a display name for the list. Go with the “Create a customizable list template and a list instance of it” and choose the Document Library.

Adding a Reference to the Microsoft Office Word Server Assembly

To use Word Automation Services, you must add a reference to the Microsoft.Office.Word.Server to the solution.

To add a reference to the Microsoft Office Word Server Assembly

  1. In Visual Studio, from the Project menu, select Add Reference.
  2. Locate the assembly. By using the Browse tab, locate the assembly. The Microsoft.Office.Word.Server assembly is located in the SharePoint 2013 ISAPI folder. This is usually located at c:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions15ISAPI. After the assembly is located, click OK to add the reference.

Adding an Event Receiver

This article uses an event receiver that uses the Microsoft.Office.Word.Server assembly to create document conversion jobs and add them to the Word Automation Services conversion job queue.

To add an event receiver

  1. In Visual Studio, on the Project menu, click Add New Item.
  2. In the Add New Item dialog box, in the Project Templates pane, click the Visual C# SharePoint 2013 template.
  3. In the Templates pane, click Event Receiver.
  4. Name the event receiver ConvertWordToPDFEventReceiver and then click Add.

    The event receiver converts Word Documents after they are added to the List. Select the An item was added item from the list of events that can be handled.

  5. Click Finish to add the event receiver to the project.

Adding the Sample Code to the Solution

Replace the contents of the ConvertWordToPDFEventReceiver.cs source file with the following code. Just remember to make sure you replace “Word Automation Services” with the name of it in the web applications in central admin.

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

using Microsoft.Office.Word.Server.Conversions;

namespace ConvertWordToPDF.ConvertWordToPDFEventReceiver
{
  /// <summary>
  /// List Item Events
  /// </summary>
  public class ConvertWordToPDFEventReceiver : SPItemEventReceiver
  {
    /// <summary>
    /// An item was added.
    /// </summary>
    public override void ItemAdded(SPItemEventProperties properties)
    {
      base.ItemAdded(properties);

      // Verify the document added is a Word document
      // before starting the conversion.
      if (properties.ListItem.Name.Contains(".docx") 
        || properties.ListItem.Name.Contains(".doc"))
      {
        //Variables used by the sample code.
        ConversionJobSettings jobSettings;
        ConversionJob pdfConversion;
        string wordFile;
        string pdfFile;

        // Initialize the conversion settings.
        jobSettings = new ConversionJobSettings();
        jobSettings.OutputFormat = SaveFormat.PDF;

        // Create the conversion job using the settings.
        pdfConversion = 
          new ConversionJob("Word Automation Services", jobSettings);

        // Set the credentials to use when running the conversion job.
        pdfConversion.UserToken = properties.Web.CurrentUser.UserToken;

        // Set the file names to use for the source Word document
        // and the destination PDF document.
        wordFile = properties.WebUrl + "/" + properties.ListItem.Url;
        if (properties.ListItem.Name.Contains(".docx"))
        {
          pdfFile = wordFile.Replace(".docx", ".pdf");
        }
        else
        {
          pdfFile = wordFile.Replace(".doc", ".pdf");
        }

        // Add the file conversion to the conversion job.
        pdfConversion.AddFile(wordFile, pdfFile);

        // Add the conversion job to the Word Automation Services 
        // conversion job queue. The conversion does not occur
        // immediately but is processed during the next run of
        // the document conversion job.
        pdfConversion.Start();

      }
    }
  }
}

Deploy and enjoy!

Published by Jared Meredith

Principal Architect with 15+ years’ experience with expertise in all things Enterprise Architecture.
View all posts by Jared Meredith

Requirement: Convert Word document into PDF in SharePoint Online.

Here is a nifty trick to convert word documents to PDF in SharePoint Online without using any 3rd party tools.

Prerequisites: Make sure the library is in “Classic Experience”. You can change the UI from modern experience to classic by clicking on the “Return to classic SharePoint” link at the bottom-left corner of the page or by going to the list settings >> Advanced Settings >>Set the “List experience” to “Classic experience.”

  1. Navigate to your SharePoint Online library where the Word document is stored. Click on the little three dots next to the document you wish to convert. 
  2. In the preview panel, click on the little “menu” icon and then choose “Print to PDF” menu item. how to convert word to pdf in sharepoint online
  3. This converts the Word document into PDF and prompts with a “Your PDF is ready to print” message. Click on the “Open PDF” button to view the converted PDF.

The converted PDF document will be opened in a new tab. You can download the PDF from the toolbar in the top-right corner.

Salaudeen Rajack

Salaudeen Rajack — SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

April 2023 Community Newsletter

Welcome to our April 2023 Community Newsletter, where we’ll be highlighting the latest news, releases, upcoming events, and the great work of our members inside the Biz Apps communities. You can subscribe to the News & Announcements and stay up to date with the latest news from our ever-growing membership network who quickly discover that «Community is bigger on the inside». 
 

 
 
LATEST NEWS
Microsoft Business Applications Launch Event — On Demand
Sign up below for an in-depth look into the latest updates from across Microsoft #PowerPlatform and #Dynamics365. Find out about new features, capabilities, and best practices for connecting data to deliver exceptional customer experiences, collaborating using AI-powered analytics, and driving productivity with automation. Guest speakers include Charles Lamanna, Emily He, Georg Glantschnig, Julie Strauss, Jeff Comstock, Lori Lamkin, Mike Morton, Ray Smith, and Walter Sun.
 

Watch Now: Business Applications Launch Event

 
 
Power Platform Connections — Episode Nine
Episode Nine of #PowerPlatform Connections premieres today at 12pm PST, as David Warner II and Hugo Bernier chat to Principal Program Manager Vesa Juvonen, alongside the great work of Troy Taylor, Geetha Sivasailam, Michael Megel, Nathalie Leenders, Ritesh Ranjan Choubey, Clay Wesener, Tristan DEHOVE, Dian Taylor, and Cat Schneider.
Click the link below to subscribe and get notified, with David and Hugo LIVE in the YouTube chat from 12pm PST. And remember to use the hashtag #PowerPlatformConnects on social to have your work featured on the show!
 

 
 
App in a Day — Free Workshop
Looking for a way to build a solution to quickly meet your business needs? Register below for a FREE «App in a Day» workshop to find out how to create custom business applications without writing code!
Microsoft Power Platform In a Day workshops

 
UPCOMING EVENTS
Directions Asia
Find out more about Directions 4 Partners Asia 2023, which will be taking place in Bangkok on 27-28th April 2023, featuring key speakers Mike Morton, Jannik Bausager and Dmitry Chadayev.
This event is for SMB focused Dynamics partners and their employees to receive product knowledge about Business Central, Power Platform and #DynamicsSales, and to be inspired and motivated by best practices, expert knowledge and innovative ideas.
If you want to meet industry experts, gain an advantage in the SMB-market, and acquire new knowledge about #MicrosoftDynamics Business Central, click the link below to buy your ticket today!
 
Click here to Register  

 
 
Iberian Tech Summit
Come take a look at the Iberian Technology Summit which will be held at the Real Marina Hotel & Spa in Olhão, Portugal, between 28-30th April 2023.
The Iberian Technology Summit is the first of its kind with a clear goal to achieve — cross the borders of peninsula and help to empower the community of professionals, workers and businesses to grow stronger together.
Congrats to Kaila Bloomfield, Adam B., Ana Inés Urrutia de Souza and the team for putting together this great event. Click below to find out more details.
Click here to Register

 
 
Power Platform Conference 2023
We are so excited to see you for the Microsoft Power Platform Conference in Las Vegas October 3-5th, 2023! But first, let’s take a look back at some fun moments and the best community in tech from MPPC 2022 in Orlando Florida.
 

Featuring guest speakers such as Heather Cook, Julie Strauss, Nirav Shah, Ryan Cunningham, Sangya Singh, Stephen Siciliano, Hugo Bernier and many more, click the link below to register for the 2023 #MPPC23 today! 
www.powerplatformconf.com
 
COMMUNITY HIGHLIGHTS
Check out our top Super and Community Users reaching new levels! These hardworking members are posting, answering questions, kudos, and providing top solutions in their communities.
Power Apps: 
Super Users:  @BCBuizer , @WarrenBelz, 
Community Users: @mmollet, @Amik, @RJM07 
 
Power Automate: 
Super Users: @Expiscornovus , @grantjenkins, @abm 
Community Users: @Nived_Nambiar  
 
Power Virtual Agents: 
Super Users: @Expiscornovus, @Pstork1, 
Community Users: @nikviz, @DaniBaeyens 
 
Power Pages:
Super Users: @ragavanrajan 
Community Users: @OOlashyn, @gospa, @Fubar 

LATEST PRODUCT BLOG ARTICLES 
Power Apps Community Blog 
Power Automate Community Blog 
Power Virtual Agents Community Blog 
Power Pages Community Blog 

Check out ‘Using the Community’ for more helpful tips and information: 
Power Apps, Power Automate, Power Virtual Agents, Power Pages 

Table of Contents

  • Case
  • Code
  • Error in PowerShell
  • Error in ULS
  • Solution

Case

An error as described below during the docx to pdf conversion using Word Automation Service Application in
SharePoint 2013.

Code

#Add-PSSnapin Microsoft.SharePoint.PowerShell
# Input parameters for the script
#$listUrl="Approved Agreement Forms"
$listUrl="All Agreement Forms under process"

# Get the Word Automation Service Proxy
$wasp = Get-SPServiceApplicationProxy | where { $_.TypeName -eq "Word Automation Services Proxy" }

#Create the Conversion job
$conversionJob = New-Object Microsoft.Office.Word.Server.Conversions.ConversionJob($wasp)

# Get the web url
$web = Get-SPWeb "https://myserver/sites/mysite"

# Set the credentials to use when running the conversion job.
$conversionJob.UserToken = $web.CurrentUser.UserToken

# Conversion Job Name
$conversionJob.Name = "ConvertDOCXtoPDF1"
$conversionJob.Settings.OutputFormat = [Microsoft.Office.Word.Server.Conversions.SaveFormat]::PDF
$conversionJob.Settings.UpdateFields = $true
$conversionJob.Settings.OutputSaveBehavior = [Microsoft.Office.Word.Server.Conversions.SaveBehavior]::AlwaysOverwrite

#Get list
$list = $web.Lists[$listUrl]
foreach ($itm in $list.Items){

for ($i =0; $i >=2; $i++) {
    if($itm.File.Name.ToLower().EndsWith(".docx") -eq $true) {
        Write-Host $($itm.File.ServerRelativeUrl)
        $conversionJob.AddFile($($web.Site.MakeFullUrl($itm.File.ServerRelativeUrl)), $($web.Site.MakeFullUrl($itm.File.ServerRelativeUrl).ToLower().Replace(".docx", ".pdf")))
        
    }
    }
}

# Start the conversion job
$conversionJob.Start()

Error in PowerShell

Exception calling «Start» with «0» argument(s): «The service application required to complete this request is not currently available.
Try this operation again later. If the problem persists, contact your administrator.»

At D:_MigrationDocument Conversion.ps1:34 char:1

+ $conversionJob.Start()

+ ~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : SPException

When you look at the ULS logs , it is not at generating the logs due to memory was hitting 100% when it finds some memory found below clue in ULS.

Error in ULS

Error: Enable ULS and   Filter the ULS logs with  Product is equal to Word Automation Services.

Proxy ‘DWProd Word Automation Services’: Exception connecting to service application: System.ServiceModel.ServiceActivationException: The requested service, ‘http://myserver:32843/fc23852d4cbc4511b3be479864b55de3/Service.svc’ could not be activated. See
the server’s diagnostic trace logs for more information. 

When you browse  this URL ‘http://myserver:32843/fc23852d4cbc4511b3be479864b55de3/Service.svc: Server is having less than 5% of memory , try after some time. Forgot to take snap shot.

Solution

Release the server from hitting 100% memory and rerun the code by limiting the number of PDF conversion to lesser number in our case it is set to 25.

  • Remove From My Forums
  • Question

  • Hi,

       How can I change a word document to pdf in sharepoint? I can download a word file and convert it to pdf.

       But I want to replace it on the sharepoint server with the new pdf file.

       For example,

        I have a test.doc file in «Shared Documents» with latest version 2.0. Now if I do some process say «publish to pdf» then it should upload the new generated pdf instead of .doc document as version 3.0.

       Can anybody let me know how to replace .doc file with .pdf file on sharepoint server.

    Thanks,

    Mehul

Answers

    • Proposed as answer by

      Wednesday, December 7, 2011 9:01 AM

    • Marked as answer by
      Shimin Huang
      Friday, December 16, 2011 6:57 AM

Понравилась статья? Поделить с друзьями:
  • Sharepoint list and excel
  • Sharepoint infopath to excel
  • Sharepoint export list to excel
  • Sharepoint excel совместное редактирование
  • Sharepoint excel services что это