Ritesh
Ritesh

Reputation: 21

How to generate Pdf file from Word/Excel file using C#?

I want to generate PDF files from Word Documents(.doc, .docx) or excel documents(.xls,.xlsx). I tried using ITextSharp but with that I am not able to render the images/tables etc of word document into the pdf.

Upvotes: 1

Views: 9211

Answers (3)

Justin
Justin

Reputation: 686

You can use Spire.Xls and Spire.Doc to do so.

Here is sample code.

    //xls to pdf        
    Workbook workbook = new Workbook();
    workbook.LoadFromFile("sample.xlsx", ExcelVersion.Version2007);
    PdfConverter pdfConverter = new PdfConverter(workbook);

    PdfDocument pdfDocument = new PdfDocument();
    pdfDocument.PageSettings.Orientation = PdfPageOrientation.Landscape;
    pdfDocument.PageSettings.Width = 970;
    pdfDocument.PageSettings.Height = 850;

    PdfConverterSettings settings = new PdfConverterSettings();
    settings.TemplateDocument = pdfDocument;
    pdfDocument = pdfConverter.Convert(settings);
    pdfDocument.SaveToFile("test.pdf");

    //doc to pdf
    Document doc = new Document();
    doc.LoadFromFile("sample.docx", FileFormat.Docx);
    doc.SaveToFile("test.pdf", FileFormat.PDF);

Upvotes: 1

Andrew
Andrew

Reputation: 10033

Here is an example of opening the word file using interops in VS2010 C#

I found this on another website hope it helps. Seems to be based around the plugin that is available for office to save as PDF.

'Save as PDF' add-on for Office 2007, check out this link

http://news.com.com/Microsoft+delivers+Save+as+PDF+add-on/2100-1012_3-6114752.html

2007 Microsoft Office Add-in: Microsoft Save as PDF - download link

http://www.microsoft.com/downloads/details.aspx?familyid=F1FC413C-6D89-4F15-991B-63B07BA5F2E5&displaylang=en

Once you download this Addin, I think you should be able to conver to PDF using Word Objects in .NET.

Otherwise,you have a third party component written in .net which does that for you, but the evaluation version produces a watermark in the converted documents, check the below link and if you are ready to purchase it then you can use it in your vb.net/c#.net code to convert doc to pdf

http://www.aspose.com/Wiki/default.aspx/Aspose.Pdf/WordToPDF.html

Upvotes: 2

Use Office Interop to open the documents in Word/Excel, and publish to PDF (if you have 2007) or print using CutePDF Writer or something like that.

Upvotes: 1

Related Questions