[TIP] Exportar Word a PDF desde Código
Mini artículo para exportar un fichero word a PDF desde código c# y VB.NET.
Al Lio
Para poder trabajar con documentos de Word en nuestro código es necesario que agreguemos la referencia “Microsoft.Office.Interop.Word.dll”.
Sin mas dilación el código:
VB.NET
1: Dim app As New Microsoft.Office.Interop.Word.Application()
2:
3: Dim missing As Object = System.Type.Missing
4: Try
5:
6: Dim document As Microsoft.Office.Interop.Word.Document = app.Documents.Open(RutaCarta)
7: Dim nombre As String = String.Format("{0}\TEMP\Name.doc", Application.StartupPath)
8:
9: app.Visible = False
10:
11: app.ActiveDocument.ExportAsFixedFormat(String.Format("{0}\Name.pdf", Application.StartupPath), & _
12: Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, False, & _
13: Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint, & _
14: Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument)
15: document.Close()
16:
17: Catch ex As Exception
18: 'Manejar la excepción....
19: Finally
20:
21: app.Quit()
22:
23: End Try
C#
1: var app = New Microsoft.Office.Interop.Word.Application()
2: var missing = System.Type.Missing
3: try
4: {
5: var document = app.Documents.Open(RutaCarta);
6: string nombre = String.Format("{0}\TEMP\Name.doc", Application.StartupPath);
7: app.Visible = false;
8:
9: app.ActiveDocument.ExportAsFixedFormat(String.Format("{0}\Name.pdf", Application.StartupPath),
10: Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, False,
11: Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
12: Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument);
13: document.Close();
14: }
15: catch(Exception ex)
16: {
17: 'Manejar la excepción....
18: }
19: finally
20: {
21: app.Quit();
22: }
Gracias al método ExportAsFixedFormat, podremos exportar nuestro fichero Word a formato PDF o XPS…
…PERO!!!:
Podremos encontrarnos una excepción que nos dirá algo así: “Esta funcionalidad no está instalada.”.
Para poder ejecutar de forma correcta este código, necesitamos instalar un addin de Office.
Espero que os sea de utilidad.
Saludos!!!