Word to PDF conversion in Xamarin and .NET Core | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (172).NET Core  (29).NET MAUI  (192)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (209)BoldSign  (12)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (63)Flutter  (131)JavaScript  (219)Microsoft  (118)PDF  (80)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (882)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (49)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (125)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (62)Development  (613)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (37)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (488)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (41)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (368)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (30)Visual Studio Code  (17)Web  (577)What's new  (313)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)

Word to PDF conversion in Xamarin and .NET Core

Syncfusion is excited to share that Word-to-PDF conversion is now available in Xamarin and .NET Core platforms.

Cross-platform development is the future of mobile, desktop, and web application development. It provides benefits like quick deployment, lower costs, wider reach, and quick turnaround time. The adoption of cross-platform application development is increasing among enterprises and small businesses as well. The Xamarin and .NET Core platforms are being used by large numbers of developers to develop applications that target multiple platforms.

Syncfusion already provided the ability to convert Word documents to PDF in Windows Forms, WPF, ASP.NET, and ASP.NET MVC applications, but it was not extended to Xamarin and .NET Core due to the lack of a graphical API.

From the 2018 Volume 1 release (version 16.1.0.24) onwards, Syncfusion has extended the support for converting Word documents to PDF in Xamarin and .NET Core with the help of the SkiaSharp graphics library.

An illustration of the Word-to-PDF conversion process in .NET Core and Xamarin.
An illustration of the Word-to-PDF conversion process in .NET Core and Xamarin. 

Currently, the following features are available in Word-to-PDF conversion:

  • Text with formatting.
  • Table.
  • Images (PNG, JPEG, BMP and GIF).
  • Headers and footers.
  • Hyperlinks.
  • Fields like page number, date time, IF, and more.
  • Form fields and content control.
  • Textbox and Shapes.
  • Text wrapping for floating images, textbox, and shapes.
  • Footnote and endnote.
  • Line numbering.
  • Bookmark navigation.

Streamline your Word document workflow effortlessly with Syncfusion’s robust Word Library.

Converting Word to PDF in Xamarin

Let’s learn how to convert a Word document to PDF in the Xamarin platform.

Prerequisites

For Windows

  • Windows 10 (recommended)
  • Visual Studio 2015 or Visual Studio 2017 (recommended)
  • Windows 10 SDK

For macOS

  • OS X El Capitan (10.11) or newer
  • Visual Studio for Mac
  •  iOS 10 SDK and Xcode 8


Procedure

1.   Create a Cross-Platform App (Xamarin.Forms) and name it WordtoPDFdemo.

2.   Select the Blank App template and the .NET Standard option under Code Sharing Strategy.

 

3.   Right-click the .NET Standard project, select Properties, and set the Target framework of the application as .NET Standard 1.4 or higher.

4.   Add the Syncfusion.Xamarin.DocIORenderer NuGet package as a reference to the .NET Standard project in your Xamarin application.

Note: Syncfusion Xamarin components are available on nuget.org.

 

5.   Add the input Word document to the asset folder in the .NET Standard project. Right-click the Word document, select Properties, and set its build action as Embedded resource.

6.      Add a button in the MainPage.xaml file.

<!--?xml version="1.0" encoding="utf-8" ?-->
<contentpage x_class="WordToPDF.MainPage">
    <stacklayout padding="10">
        <label x_name="Content_heading" text="Word to PDF in XForms" fontsize="Large" fontattributes="Bold" horizontaloptions="Center" verticaloptions="Center"></label>
        <label x_name="Content_1" text="This sample demonstrates how to convert a Word Document to PDF using DocIORenderer." fontsize="Medium" verticaloptions="Center"></label>
        <button x_name="btnGenerate" clicked="OnButtonClicked" text="Convert to PDF" horizontaloptions="Center" verticaloptions="Center" tabindex="151"></button>
    </stacklayout>
</contentpage>

7.  Add the following code in the onButtonClicked method in the MainPage.xaml.cs file. Use the ConvertToPDF method of the DocIORenderer class to convert the WordDocument instance to a PdfDocument instance and save the PDF document to the device.

Assembly assembly = typeof(App).GetTypeInfo().Assembly;
// Retrieves the document stream from embedded Word document
Stream inputStream = assembly.GetManifestResourceStream("WordToPDF.Assets.GettingStarted.docx");
string fileName = "GettingStarted.pdf";
// Creates new instance of WordDocument
WordDocument wordDocument = new WordDocument(inputStream, Syncfusion.DocIO.FormatType.Automatic);
// Creates new instance of DocIORenderer for Word to PDF conversion
DocIORenderer render = new DocIORenderer();
// Converts Word document into PDF document
PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);
// Releases all resources used by the DocIORenderer and WordDocument instance
render.Dispose();
wordDocument.Close();
// Saves the converted PDF file
MemoryStream outputStream = new MemoryStream();
pdfDocument.Save(outputStream);
// Releases all resources used by the PdfDocument instance
pdfDocument.Close();

// Saves the PDF document to the device through the dependency service with the help of platform-specific file system API
if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
    DependencyService.Get<isavewindowsphone>().Save(fileName, "application/pdf", outputStream);
else
    DependencyService.Get<isave>().Save(fileName, "application/pdf", outputStream);

A runnable Xamarin application capable of Word to PDF conversion can be downloaded here.

Acquire an in-depth understanding of Syncfusion's Word Library, exploring its impressive features through its comprehensive documentation.

Converting Word to PDF in .NET Core application

Next, let’s learn how to convert a Word document to PDF in an ASP.NET Core application.

Prerequisites

Windows

  •  Windows 10 (recommended). Refer here for the list of supported Windows operating systems.
  •  Visual Studio 2017
  • .NET Core 1.0 SDK or newer

macOS

  •  OS X El Capitan (10.11) or newer. Refer here for the list of supported macOS operating systems.
  •  Visual Studio for Mac
  •  .NET Core 1.0 SDK or newer

Linux

  •  Ubuntu 14.04 or later version. Refer here for the list of supported Linux operating systems.
  •  .NET Core 1.0 SDK or newer

Procedure

1.      Create a new ASP.NET Core Web Application project using Core 1.0 or newer and name it WordtoPDFdemo.

 

2.      Set ASP.NET Core 2.0 as the target platform and select the Web Application (Model-View-Controller) project template.

3.    Add the Syncfusion.DocIORenderer.NetStandard NuGet package as a reference to the ASP.NET Core project from the Syncfusion ASP.NET Core NuGet feed. For more information about adding a NuGet feed in Visual Studio and installing NuGet packages, refer to our documentation.

You can also install this package from the NuGet package manager console by executing the following command.

> Install-package Syncfusion.DocIORenderer.NetStandard -source https://nuget.syncfusion.com/nuget_aspnetcore/nuget/getsyncfusionpackages/aspnetcore

 

4.      Add the following code in the index.cshtml file.

@{
    ViewData["Title"] = "Home Page";
}
@{Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" });
    {
        <div class="Common">
            <div class="tablediv">
                <div class="rowdiv">
                    This sample illustrates how to convert a Word document to PDF using Essential DocIO and Essential PDF.
                </div>
                <div class="rowdiv" style="border-width: 0.5px;border-style:solid; border-color: lightgray; padding: 1px 5px 7px 5px">
                    Click the button to view the resultant PDF document converted from a Word document using Essential DocIO and Essential PDF. Please note that a PDF viewer is required to view the resultant PDF.
                    <div class="rowdiv" style="margin-top: 10px">
                        <div class="celldiv" style="font-weight:bold">
                            Select Document :
                            @Html.TextBox("file", "", new { type = "file", accept = ".doc,.docx,.rtf,.dot,.dotm,.dotx,docm,.xml" }) <br>
                        </div>
                        <div class="rowdiv" style="margin-top: 8px">
                            <input class="buttonStyle" value="Convert to PDF" name="button" style="width:150px;height:27px" type="submit" tabindex="159">
                            <br>
                            <div class="text-danger">
                                @ViewBag.Message
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        Html.EndForm();
    }}

5. Add the following code to get the Word file and convert it to PDF in the HomeController.cs file.

public async System.Threading.Tasks.Task<ActionResult> Index(string button)
{
    if (button == null)
        return View();
    ViewBag.Message = string.Empty;
    if (Request.Form.Files != null)
    {
        // Gets the extension from file
        string extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();
        // Compares extension with supported extensions
        if (extension == ".doc" || extension == ".docx" || extension == ".dot" || extension == ".dotx" || extension == ".dotm" || extension == ".docm"
           || extension == ".xml" || extension == ".rtf")
        {
            MemoryStream stream = new MemoryStream();
            // Retrieves the document stream
            Request.Form.Files[0].CopyTo(stream);
            try
            {
                //Creates new instance of WordDocument
                WordDocument document = new WordDocument(stream, FormatType.Automatic);
                stream.Dispose();
                stream = null;
                // Creates new instance of DocIORenderer for Word to PDF conversion
                DocIORenderer render = new DocIORenderer();
                // Converts Word document into PDF document
                PdfDocument pdf = render.ConvertToPDF(document);
                // Saves the converted PDF file
                MemoryStream memoryStream = new MemoryStream();                         
                pdf.Save(memoryStream);
                // Releases all resources used by the DocIORenderer and WordDocument instance
                render.Dispose();
                document.Close();
                // Releases all resources used by the PdfDocument instance
                pdf.Close();
                memoryStream.Position = 0;
                
                return File(memoryStream, "application/pdf", "WordToPDF.pdf");
            }
            catch (Exception ex)
            {
                ViewBag.Message = string.Format("The input document could not be processed completely. Please email the document to support@syncfusion.com for troubleshooting.");
            }
        }
        else
        {
            ViewBag.Message = string.Format("Please choose a Word format document to convert to PDF");
        }
    }
    else
    {
        ViewBag.Message = string.Format("Browse for a Word document and then click the button to convert it to a PDF document");
    }
    return View();

}   

A runnable .NET Core application capable of Word to PDF conversion can be downloaded here.

Refer to the procedure to deploy your .NET Core application in a Linux OS here.

Discover the user-friendly features of the Syncfusion Word Library, reshaping your document creation process with ease.

Conclusion

Users can now convert Word documents to PDF in cross-platform applications (Xamarin and .NET Core) without relying on web services. These applications can run on Windows, Android, Mac, iOS, and Linux.

You can convert an existing Word document or create a Word document from scratch, perform mail merge using the DocIO library, and then convert it to a PDF as required. If you are new to our DocIO library, it is highly recommended to follow our Getting Started guide.

If you’re already a Syncfusion user, you can download the product setup here. If you’re not yet a Syncfusion user, you can download a free, 30-day trial here.

If you have any questions or require clarification about this feature, please let us know in the comments below. You can also contact us through our support forum or Direct-Trac. We are happy to assist you!

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed
Scroll To Top