I need to convert from word to pdf in c# by using ITextSharp
Loading
I need to convert from word to pdf in c# by using ITextSharp
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit MohantyRank #112 · 20K reputationPosted Jul 15, 2024, 3:31 AM EDT
Install iTextSharp and DocX via NuGet Package Manager.
using System; using System.IO; using Xceed.Words.NET; using iTextSharp.text; using iTextSharp.text.pdf; class Program { static void Main(string[] args) { string wordFilePath = @"path\to\your\wordfile.docx"; string pdfFilePath = @"path\to\your\pdffile.pdf"; var doc = DocX.Load(wordFilePath); using (FileStream fs = new FileStream(pdfFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { Document pdfDoc = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, fs); pdfDoc.Open(); foreach (var paragraph in doc.Paragraphs) { pdfDoc.Add(new Paragraph(paragraph.Text)); } pdfDoc.Close(); } Console.WriteLine("Conversion completed successfully!"); } }Adarsh NigamRank #950 · 2.1K reputationPosted Jul 15, 2024, 12:49 PM EDT
To convert an Arabic Word file to PDF and ensure that the Arabic text is displayed correctly, you need to embed a font that supports Arabic characters in the PDF document. The default fonts used by iTextSharp might not support Arabic, leading to the text not appearing correctly. Here's an updated version of your code that uses a font supporting Arabic characters.
First, ensure you have an Arabic-supporting font file (e.g., `arialuni.ttf`) in your project directory.
--------------------------------------<><><><><><><><><>---------------------------------------------
### Updated Code
using System;
using System.IO;
using Xceed.Words.NET;
using iTextSharp.text;
using iTextSharp.text.pdf;
class Program
{
static void Main(string[] args)
{
string wordFilePath = @"path\to\your\wordfile.docx";
string pdfFilePath = @"path\to\your\pdffile.pdf";
string fontPath = @"path\to\your\arialuni.ttf"; // Path to a font that supports Arabic characters
var doc = DocX.Load(wordFilePath);
using (FileStream fs = new FileStream(pdfFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
Document pdfDoc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, fs);
pdfDoc.Open();
// Load the font that supports Arabic characters
BaseFont baseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(baseFont, 12);
foreach (var paragraph in doc.Paragraphs)
{
pdfDoc.Add(new Paragraph(paragraph.Text, font));
}
pdfDoc.Close();
}
Console.WriteLine("Conversion completed successfully!");
}
}
### Steps to Follow
1. **Download and Install the Required Packages**
Ensure you have the necessary NuGet packages installed:
Install-Package itextsharp
Install-Package DocX
2. **Ensure a Font Supporting Arabic Characters**
Download a font that supports Arabic characters, such as `arialuni.ttf`. Place this font file in your project directory.
3. **Update the Paths**
Update the `wordFilePath`, `pdfFilePath`, and `fontPath` variables with the correct paths to your Word file, output PDF file, and the font file respectively.
4. **Run the Code**
Execute the program. The Arabic text in the Word document should now be correctly converted and displayed in the PDF file.
### Explanation
- **BaseFont and Font Initialization**:
- `BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED)`: This initializes a font that supports Unicode characters, ensuring that Arabic text is rendered correctly.
- `Font font = new Font(baseFont, 12)`: This creates a font instance with a specified size using the base font.
--------------------------------------<><><><><><><><><>---------------------------------------------
- **Adding Paragraphs with the Specified Font**:
- The `new Paragraph(paragraph.Text, font)` ensures that each paragraph from the Word document is added to the PDF using the specified font, which supports Arabic characters.
By following these steps and using the updated code, you should be able to convert an Arabic Word file to a PDF correctly.
--------------------------------------<><><><><><><><><>---------------------------------------------
rasha galal10 reputationPosted Jul 15, 2024, 9:33 AM EDT
I excuted this code, but it didn't convert arabic word file to pdf correctly, the arabic text doesnot appear, how can i convert arabic word file to pdf ??
Vishal JoshiRank #377 · 6.7K reputationPosted Jul 16, 2024, 2:23 AM EDT
Hello Rasha,
To convert a Word file to a PDF in C#, you can use the Microsoft Office Interop library if you have Microsoft Office installed on your machine, or you can use the Open XML SDK along with a third-party library like Open XML PowerTools. Below are examples of both methods:
Method 1: Using Microsoft Office Interop
Add a reference to
Microsoft.Office.Interop.Word:Microsoft Word XX.0 Object Library(where XX is the version number).using System; using Microsoft.Office.Interop.Word; namespace WordToPdfConversion { class Program { static void Main(string[] args) { Application wordApp = new Application(); wordApp.Visible = false; object missing = Type.Missing; object readOnly = true; object addToRecentFiles = false; object fileFormat = WdSaveFormat.wdFormatPDF; string sourcePath = @"C:\path\to\your\document.docx"; string targetPath = @"C:\path\to\your\document.pdf"; Document wordDocument = wordApp.Documents.Open(ref sourcePath, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wordDocument.SaveAs2(ref targetPath, ref fileFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); wordDocument.Close(ref missing, ref missing, ref missing); wordApp.Quit(ref missing, ref missing, ref missing); Console.WriteLine("Conversion complete!"); } } }Method 2: Using Open XML SDK and Open XML PowerTools
using System; using System.IO; using DocumentFormat.OpenXml.Packaging; using OpenXmlPowerTools; using PdfSharp.Pdf; using PdfSharp.Drawing; namespace WordToPdfConversion { class Program { static void Main(string[] args) { string sourcePath = @"C:\path\to\your\document.docx"; string targetPath = @"C:\path\to\your\document.pdf"; byte[] byteArray = File.ReadAllBytes(sourcePath); using (MemoryStream memoryStream = new MemoryStream()) { memoryStream.Write(byteArray, 0, byteArray.Length); using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(memoryStream, true)) { HtmlConverterSettings settings = new HtmlConverterSettings() { PageTitle = "My Page Title" }; XElement htmlElement = HtmlConverter.ConvertToHtml(wordDocument, settings); // Save the HTML content to a file string htmlContent = htmlElement.ToString(); string htmlFilePath = Path.ChangeExtension(targetPath, ".html"); File.WriteAllText(htmlFilePath, htmlContent); // Convert HTML to PDF using PdfSharp ConvertHtmlToPdf(htmlFilePath, targetPath); } } Console.WriteLine("Conversion complete!"); } } }Thanks
Vishal Joshi
Leon DRank #851 · 2.6K reputationPosted Jul 19, 2024, 5:01 AM EDT
You can try Spire.Doc to convert Word with Arabic text to PDF. Make sure your system has already installed the fonts used in your Word file.
Install-Package Spire.DocHere is a basic code example:
using Spire.Doc; namespace ConvertWordToPdf { class Program { static void Main(string[] args) { // Create a Document object Document doc = new Document(); // Load a Word document doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx"); // Save the document to PDF doc.SaveToFile("ToPDF.pdf", FileFormat.PDF); // Dispose resources doc.Dispose(); } } }Spire.Doc supports various advanced conversion options when converting Word to PDF, you can check this article for more details:
https://www.e-iceblue.com/Tutorials/Spire.Doc/Spire.Doc-Program-Guide/How-to-Convert-Word-to-PDF.html