Interop word save as pdf

Use a foreach loop instead of a for loop — it solved my problem.

int j = 0;
foreach (Microsoft.Office.Interop.Word.Page p in pane.Pages)
{
    var bits = p.EnhMetaFileBits;
    var target = path1 +j.ToString()+  "_image.doc";
    try
    {
        using (var ms = new MemoryStream((byte[])(bits)))
        {
            var image = System.Drawing.Image.FromStream(ms);
            var pngTarget = Path.ChangeExtension(target, "png");
            image.Save(pngTarget, System.Drawing.Imaging.ImageFormat.Png);
        }
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message);  
    }
    j++;
}

Here is a modification of a program that worked for me. It uses Word 2007 with the Save As PDF add-in installed. It searches a directory for .doc files, opens them in Word and then saves them as a PDF. Note that you’ll need to add a reference to Microsoft.Office.Interop.Word to the solution.

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

...

// Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;

// Get list of Word files in specified directory
DirectoryInfo dirInfo = new DirectoryInfo(@"\serverfolder");
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");

word.Visible = false;
word.ScreenUpdating = false;

foreach (FileInfo wordFile in wordFiles)
{
    // Cast as Object for word Open method
    Object filename = (Object)wordFile.FullName;

    // Use the dummy value as a placeholder for optional arguments
    Document doc = word.Documents.Open(ref filename, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    doc.Activate();

    object outputFileName = wordFile.FullName.Replace(".doc", ".pdf");
    object fileFormat = WdSaveFormat.wdFormatPDF;

    // Save document into PDF Format
    doc.SaveAs(ref outputFileName,
        ref fileFormat, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing);

    // Close the Word document, but leave the Word application open.
    // doc has to be cast to type _Document so that it will find the
    // correct Close method.                
    object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
    ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
    doc = null;
}

// word has to be cast to type _Application so that it will find
// the correct Quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;

  • Remove From My Forums
  • General discussion

  • According to

    http://office.microsoft.com/en-ca/word-help/save-as-pdf-HA010354239.aspx#BM11

    one can save from 2010 word document to PDF

    Word

    This information also applies to Microsoft Word Starter 2010.

    Check out
    Convert a document to PDF for Word 2013 steps.

      • Click the File tab.
      • Click Save As.
        To see the Save As dialog box in Word 2013, you have to choose a location and folder.
      • In the File Name box, enter a name for the file, if you haven’t already.
      • In the Save as type list, click PDF (*.pdf).
      • If you want the file to open in the selected format after saving, select the
        Open file after publishing
        check box.
      • If the document requires high print quality, click Standard (publishing online and printing).
      • If the file size is more important than print quality, click Minimum size (publishing online).
    1. Click Options to set the page to be printed, to choose whether markup should be printed, and to select output options. Click
      OK when finished.
    2. Click Save.

    I verifyied the above steps manually with my word 2010.

    When I tried from c# .net 3.5 using office.interop.Word version 14, like this

    Clipboard.SetData(System.Windows.Forms.DataFormats.Html, html);
    			object missing = Type.Missing;
    			Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    			Microsoft.Office.Interop.Word.Document document = wordApp.Documents.Add(ref missing, ref missing, ref missing, true);
    			document.Activate();
    			wordApp.Visible = true;
    			document.ActiveWindow.Selection.Paste(); //so far so good
    			document.SaveAs2(saveAsFilePathName, System.Windows.Forms.DataFormats.PDF);  // no DataFormats.PDF

    I spent fai amount of time serachign for answer wiithout luck.
    finally stumble acoross wdFormatPDF after google searching with «word interop 14  saveas fileformat»

    so

    // the last line of code
    document.SaveAs2(saveAsFilePathName, System.Windows.Forms.DataFormats.PDF); 
    // should be:
    Microsoft.Office.Interop.Word.WdSaveFormat wdSaveFmt = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
    			object oWdSaveFmt = wdSaveFmt, oSaveAsSpec = saveAsFilePathName;
    			document.SaveAs2(ref oSaveAsSpec, ref oWdSaveFmt);

    I was tempted to delete this thread bu then at least or myself, I will be able the the answer quicker in the future adn maybe comeone can contribut a better way of handling savas PDF

    • Changed type

      Tuesday, July 23, 2013 4:43 AM

    • Edited by
      fs — ab
      Tuesday, July 23, 2013 5:29 AM

Converting Office Documents to PDF

If you want to convert a document to PDF you can save it as PDF (File -> Export -> PDF). But what if you have a lot of documents you want to convert to PDF. Then the Office Interop Assemblies could help you. This blog explains how you could use the Office Interop Assemblies to convert Word, PowerPoint and Excel files to PDF.

Prerequisites:
– Microsoft Office needs to be installed
– Some dev skills

This is not something you would like to use on a large production environment. But if you are in need of a onetime solution this could be a solution. Always keep in mind that you backup your Office documents and check the results after converting.

Word

Add Assembly reference to project: Microsoft.Office.Interop.Word

Code:

var wordApp = new Microsoft.Office.Interop.Word.Application();
var wordDocument = wordApp.Documents.Open(@"C:WordDocument.docx");
           
wordDocument.ExportAsFixedFormat(@"C:NewPDFFile.PDF", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);

wordDocument.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges, 
                   Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat, 
                   false); //Close document

wordApp.Quit(); //Important: When you forget this Word keeps running in the background

PowerPoint

Add Assembly reference to project: Microsoft.Office.Interop.PowerPoint

Code:

var powerpointApp = new Microsoft.Office.Interop.PowerPoint.Application();

var powerpointDocument = powerpointApp.Presentations.Open(@"C:PowerPoint.pptx", 
                Microsoft.Office.Core.MsoTriState.msoTrue, //ReadOnly
                Microsoft.Office.Core.MsoTriState.msoFalse, //Untitled
                Microsoft.Office.Core.MsoTriState.msoFalse); //Window not visible during converting
           
powerpointDocument.ExportAsFixedFormat(@"C:NewPDFFile.pdf", 
                Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);

powerpointDocument.Close(); //Close document
powerpointApp.Quit(); //Important: When you forget this PowerPoint keeps running in the background

Excel

Add assembly reference to project: Microsoft.Office.Interop.Excel

Code:

var excelApp = new Microsoft.Office.Interop.Excel.Application();

var excelDocument = excelApp.Workbooks.Open(@"C:ExcelDocument.xlsx");

excelDocument.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, 
                                  @"C:NewPDFFile.pdf"); 

excelDocument.Close(false, "", false); //Close document
excelApp.Quit(); //Important: When you forget this Excel keeps running in the background

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
        wordDocument = appWord.Documents.Open(@"D:desktopxxxxxx.docx");
        wordDocument.ExportAsFixedFormat(@"D:desktopDocTo.pdf", WdExportFormat.wdExportFormatPDF);
    }

    public Microsoft.Office.Interop.Word.Document wordDocument { get; set; }
}

try this code… working successfully…

If you have used newer versions of MS Office, you might have noticed that we can save a Word document or Excel sheet as PDF. This is a useful feature. But how can we do this programmatically?

This post shows how to convert a Word document to PDF grammatically using C#.

To work with Word files, we need to add reference to Microsoft.Office.Interop.Word.dll first. Install it with the following command or you can also get it from NuGet.

Install-Package Microsoft.Office.Interop.Word -Version 15.0.4797.1003

Next, add required namespaces:

using Microsoft.Office.Interop.Word;

Convert Word to PDF

Here’s a small program that converts a Word file to PDF.

using Microsoft.Office.Interop.Word;
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Converting...");
            Application app = new Application();
            Document doc = app.Documents.Open(@"D:/test.docx");
            doc.SaveAs2(@"D:/test.pdf", WdSaveFormat.wdFormatPDF);
            doc.Close();
            app.Quit();
            Console.WriteLine("Completed");
        }
    }
}

Please note that a new WINWORD.exe process is started each time when you run the code. This will eat up all the memory if the Close() method is not called.

This package offers several other features also. For example, we can count the number of characters or grammatical errors in a word file.

Count the number of characters:

var c = doc.Characters;
Console.Write(c.Count);

Count grammatical errors:

var e = doc.GrammaticalErrors;
Console.WriteLine(e.Count);

Note: Like Word files, we can also convert Excel sheets and PPT files to PDF by adding appropriate packages.


Subscribe

Join the newsletter to get the latest updates.

Great! Check your inbox and click the link

Please enter a valid email address!


Who never had the urge to convert one or more MS Word DOC and DOCX files into a PDF at least once? Truth to be told, it wasn’t that trivial back in the day: until the release of Office 2010, when the PDF extension appeared among the various  formats supported by the Save As… command, using Ghostscript-based software or installing PDF printer drivers was the only way to go.

After Office 2010 the problem was finally solved even for the average user, with the sole exception that he still has to have MS Office installed on his machine. Those who didn’t have it can continue to use the aforementioned free alternatives ond purchase a software that will take care of the job for them.

What about doing that in a programmatic approach? What if we are developing a C# application and we need to convert some DOC or DOCX files into PDF, thus making then available to download without giving the source document to the users, possibly without having to waste an Office license to our web server/web publishing machine?

The answer, still MS-branded, comes by the name of Microsoft Office primary interop assemblies (PIAs), aka Microsoft Office Interop. Specifically, to work with Word files, you’re going to need the Microsoft.Office.Interop.Word.dll. If you’re using Visual Studio, you can get it from NuGet and attach to your application using the Package Explorer, otherwise you will have to download and install the official distribution package.

As soon as you do that, you’ll be able to open and edit any MS Word document from the FileSystem or from a Byte Array, as explained in this post. Here’s a brief example showing what you can do:

// NS alias to avoid writing the required namespace all the time

using word = Microsoft.Office.Interop.Word;

// […]

Application app = new word.Application();

Document doc = app.Documents.Open(filePath);

doc.SaveAs2(«path-to-pdf-file.pdf», word.WdSaveFormat.wdFormatPDF);

doc.Close();

app.Quit();

Alternatively, if you don’t like the SaveAs2 method, you can use the ExportAsFixedFormat() method instead and achieve a nearly identical result:

doc.ExportAsFixedFormat(tmpFile, WdExportFormat.wdExportFormatPDF);

It’s worth noting that everything we said about MS Word can also be done with the other software contained within the MS Office bundle such as MS Excel, MS Powerpoint and more.

IMPORTANT: Do not underestimate the call to

app.Quit()

! If you don’t do that, the MS Word instance will be left open on your server (see this thread on StackOverflow for more info on that issue). If you want to be sure to avoid such dreadful scenario entirely you should strengthen the given implementation adding a try/catch fallback strategy such as the follow:

Application app = null;

Document doc = null;

try

{

    app = new word.Application();

    doc = Document doc = app.Documents.Open(filePath);

    // .. do your stuff here …

    doc.Close();

    app.Quit();

}

catch (Exception e)

{

    if (doc != null) doc.Close();

    if (app != null) app.Quit();

}

Unfortunately these objects don’t implement


IDisposable

, otherwise it would’ve been even easier.

That’s about it: happy converting!

UPDATE: in case you run into DCOM issues and/or permission errors when publishing your web application project based upon the Microsoft.Office.Interop package into a Windows Server + IIS production machine, read this post to fix them!

using System; using Microsoft.Office.Interop.Word; using Word = Microsoft.Office.Interop.Word; namespace WordToPDFConsoleApp { class Program { static void Main(string[] args) { /* * Convert Input.docx into Output.pdf * Please note: You must have the Microsoft Office 2007 Add-in: Microsoft Save as PDF or XPS installed * http://www.microsoft.com/downloads/details.aspx?FamilyId=4D951911-3E7E-4AE6-B059-A2E79ED87041&displaylang=en * Solution source http://cathalscorner.blogspot.com/2009/10/converting-docx-into-doc-pdf-html.html */ Convert(C:UsersArthurWordToPDFFilesTestMemoDoc — Copy — Copy — Copy.docx«, C:UsersArthurWordToPDFFilesTestMemoDoc — Copy — Copy — Copy.pdf«, WdSaveFormat.wdFormatPDF); Console.WriteLine(«Document… Converted!«); Console.ReadKey(); } // Convert method public static void Convert(string input, string output, WdSaveFormat format) { // Create an instance of Word.exe _Application oWord = new Word.Application { // Make this instance of word invisible (Can still see it in the taskmgr). Visible = false }; // Interop requires objects. object oMissing = System.Reflection.Missing.Value; object isVisible = true; object readOnly = true; // Does not cause any word dialog to show up //object readOnly = false; // Causes a word object dialog to show at the end of the conversion object oInput = input; object oOutput = output; object oFormat = format; // Load a document into our instance of word.exe _Document oDoc = oWord.Documents.Open( ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); // Make this document the active document. oDoc.Activate(); // Save this document using Word oDoc.SaveAs(ref oOutput, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); // Always close Word.exe. oWord.Quit(ref oMissing, ref oMissing, ref oMissing); } } }

Recently, I had a great interest in how to convert Office documents to PDF or XPS. Therefore, I collected lots of materials. Now, I want to share a method I think is useful.

First, Office SaveAs PDF and XPS (an Add-in for Office 2007) needs to be installed. You can download it from the Microsoft official website.

Then, open VS. Take VS 2005 as an example. Create a new Windows application project and add the following COM components as references.

Microsoft Word 12.0 Object Library
Microsoft PowerPoint 12.0 Object Library
Microsoft Excel 12.0 Object Library

using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;

We can use bool to determine the format of generated files.

Word.WdExportFormat wd = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
Excel.XlFixedFormatType excelType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
PowerPoint.PpSaveAsFileType ppType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF;

In this method, I use ExportAsFixedFormat for Word and Excel and SaveAs for Powerpoint.

Actually, the SaveAs method can support several formats. Therefore, we can also use SaveAs for Word. However, it cannot be used for Excel.

Convert Word to PDF

private bool Convert(string sourcePath, string targetPath, Word.WdExportFormat exportFormat)
{
    bool result;
    object paramMissing = Type.Missing;
    Word.ApplicationClass wordApplication = new Word.ApplicationClass();
    Word.Document wordDocument = null;
    try
    {
         object paramSourceDocPath = sourcePath;
         string paramExportFilePath = targetPath;
         Word.WdExportFormat paramExportFormat = exportFormat;
         bool paramOpenAfterExport = false;
         Word.WdExportOptimizeFor paramExportOptimizeFor =
         Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
         Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
          int paramStartPage = 0;
          int paramEndPage = 0;
          Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
          bool paramIncludeDocProps = true;
          bool paramKeepIRM = true;
          Word.WdExportCreateBookmarks paramCreateBookmarks =
          Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
          bool paramDocStructureTags = true;
          bool paramBitmapMissingFonts = true;
          bool paramUseISO19005_1 = false;
          wordDocument = wordApplication.Documents.Open(
                                 ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                                 ref paramMissing, ref paramMissing, ref paramMissing,
                                 ref paramMissing, ref paramMissing, ref paramMissing,
                                 ref paramMissing, ref paramMissing, ref paramMissing,
                                 ref paramMissing, ref paramMissing, ref paramMissing,
                                 ref paramMissing);

          if (wordDocument != null)
              wordDocument.ExportAsFixedFormat(paramExportFilePath,
              paramExportFormat, paramOpenAfterExport,
              paramExportOptimizeFor, paramExportRange, paramStartPage,
              paramEndPage, paramExportItem, paramIncludeDocProps,
              paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
              paramBitmapMissingFonts, paramUseISO19005_1,
              ref paramMissing);
              result = true;
    }
    finally
    {
        if (wordDocument != null)
        {
            wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
            wordDocument = null;
        }
        if (wordApplication != null)
        {
            wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
            wordApplication = null;
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
    return result;
}

Convert Excel to PDF

private bool Convert(string sourcePath, string targetPath, XlFixedFormatType targetType)
{
    bool result;
    object missing = Type.Missing;
    ApplicationClass application = null;
    Workbook workBook = null;
    try
    {
        application = new ApplicationClass();
        object target = targetPath;
        object type = targetType;
        workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                           missing, missing, missing, missing, missing, missing, missing, missing, missing);
        workBook.ExportAsFixedFormat(targetType, target, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
        result = true;
    }
    catch
    {
        result = false;
    }
    finally
    {
        if (workBook != null)
        {
            workBook.Close(true, missing, missing);
            workBook = null;
        }
        if (application != null)
        {
            application.Quit();
            application = null;
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
    return result;

}

By the way, I found a Free PDF Converter which can convert office files to PDF. That Free PDF Converter is also created via C#.

Convert PowerPoint to PDF

private bool Convert(string sourcePath, string targetPath, PpSaveAsFileType targetFileType)
{
        bool result;
        object missing = Type.Missing;
        ApplicationClass application = null;
        Presentation persentation = null;
        try
        {
                application = new ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);

                result = true;
        }
        catch
        {
                result = false;
        }
        finally
        {
                if (persentation != null)
                {
                        persentation.Close();
                        persentation = null;
                }
                if (application != null)
                {
                        application.Quit();
                        application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
        }
        return result;
}

If we want to convert Word or Excel to XPS, we can use XPS virtual printer. After installing .Net Framework 3.5, the XPS virtual printer will be installed by default. And we set it as the default printer.

Microsoft XPS Document Writer

Word to XPS

public void PrintWord(string wordfile)
{
        oWord.ApplicationClass word = new oWord.ApplicationClass();
        Type wordType = word.GetType();

        //Open Word Document

        oWord.Documents docs = word.Documents;
        Type docsType = docs.GetType();
        object objDocName = wordfile;
        oWord.Document doc = (oWord.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { objDocName, true, true });

        //Print and Export to Specified File
        //Use doc.PrintOut(); method. But it is complicated to call the parameters. Suggest to use Type.InvokeMember. We just set four main parameters to call PrintOut.

        Type docType = doc.GetType();
        object printFileName = wordfile + ".xps";
        docType.InvokeMember("PrintOut", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { false, false, oWord.WdPrintOutRange.wdPrintAllDocument, printFileName });

        //Quit Word
        wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
}

Excel to XPS

public void PrintExcel(string execlfile)
{
        Excel.ApplicationClass eapp = new Excel.ApplicationClass();
        Type eType = eapp.GetType();
        Excel.Workbooks Ewb = eapp.Workbooks;
        Type elType = Ewb.GetType();
        object objelName = execlfile;
        Excel.Workbook ebook = (Excel.Workbook)elType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, Ewb, new Object[] { objelName, true, true });

        object printFileName = execlfile + ".xps";

        Object oMissing = System.Reflection.Missing.Value;
        ebook.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, true, oMissing, printFileName);

        eType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, eapp, null);
}

In the same manner, if a PDF virtual printer is installed on the computer, for example, 5D PDF, we can set it as the default printer to convert other formats to PDF.

Also, we can put the methods in a Windows Service to do background conversion of documents.

В данной статье я покажу как при помощи языка C# переконвертировать файл word в pdf и xps.

Для начала создайте консольный проект в Visual Studio с названием WordToPdfAndXps.

После его создания необходимо добавить в References библиотеку для работы с Word.

add reference visual studio

Раскрываем вкладку COM и выбираем подраздел Type Libraries. Затем ставим галочку напротив библиотеки Microsoft Word 14.0 Object Library. Возможно у вас будет другая версия, но я тестирую с этой.

add Microsoft Word 14.0 Object Library

Далее пишем следующий код и программа готова:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

using System;

using Microsoft.Office.Interop.Word; // подключаем библиотеку для работы с Word

namespace WordToPdfAndXps

{

    class Program

    {

        static void Main(string[] args)

        {

            string path = @»D:texts»; // прописываем путь к папке с файлами для удобства

            Application word = new Application(); // создаём экземпляр приложения Word

            Document file = word.Documents.Open(path + «info.docx»); // создаём экземпляр документа и открываем word файл

            file.ExportAsFixedFormat(path + «info_pdf.pdf», WdExportFormat.wdExportFormatPDF); // преобразование файла в PDF формат

            file.ExportAsFixedFormat(path + «info_xps.xps», WdExportFormat.wdExportFormatXPS); // преобразование файла в XPS формат

            word.Quit(); // закрываем Word

            Console.WriteLine(«Конвертация завершена.nНажмите любую клавишу…»); // вывод сообщения

            Console.ReadKey(); // ожидание нажатия любой клавиши

        }

    }

}

Если у вас имеются вопросы, можете обращаться в комментарии.

Загрузка…

EVG-1980

192 / 199 / 82

Регистрация: 11.04.2013

Сообщений: 1,086

1

13.05.2014, 13:09. Показов 2792. Ответов 14

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Имеем word 2003 и вот это

C#
1
2
3
4
5
6
7
object outputFileName = System.IO.Path.ChangeExtension(pathfile, "pdf");
object fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
doc.SaveAs(ref outputFileName, ref fileFormat, ref _MissingValue, ref _MissingValue,
ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue);

При выполнении кода получаем сообщение от wordа что для этого файла требуется более новый конвертер файлов Microsoft Works 6–9 и отправляет сюда http://www.microsoft.com/ru-ru… aspx?id=12

скачал установил эффекта ноль прошу помощи



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

13.05.2014, 13:09

Ответы с готовыми решениями:

Посоветуйте библиотеку для формирования отчетов в *.pdf, *.doc, *.xls
Доброго времени суток, уважаемые форумчане!
В очередной раз поднимаю вопрос об отчетах в C#.NET….

Экспорт в doc или в pdf
добрый день, у меня еще очень небольшой экспириенс в asp.net, поэтому прошу помощи…
итак, нужно…

Генерация DOC и PDF в asp.net проекте
Добрый день требуется найти оптимальное решение для генерации DOC и PDF документов.

1) У…

Сервер не находит некоторые типы файлов(.pdf, .ppt, .doc) если к ним обращаться напрямую.
Появилась такая большая проблема: Сервер не находит некоторые типы файлов(.pdf, .ppt, .doc) если к…

14

Gul-79

48 / 48 / 11

Регистрация: 13.08.2012

Сообщений: 97

13.05.2014, 15:11

2

C#
1
2
doc.ExportAsFixedFormat(path, WdExportFormat.wdExportFormatPDF,
                false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument);



0



192 / 199 / 82

Регистрация: 11.04.2013

Сообщений: 1,086

13.05.2014, 15:21

 [ТС]

3

Gul-79, с этой штукой тоже побывал вываливается

Кликните здесь для просмотра всего текста

System.AccessViolationException не обработано
Message=Попытка чтения или записи в защищенную память. Это часто свидетельствует о том, что другая память повреждена.
Source=WordInPdf
StackTrace:
в Microsoft.Office.Interop.Word._Document.ExportAsFi xedFormat(String OutputFileName, WdExportFormat ExportFormat, Boolean OpenAfterExport, WdExportOptimizeFor OptimizeFor, WdExportRange Range, Int32 From, Int32 To, WdExportItem Item, Boolean IncludeDocProps, Boolean KeepIRM, WdExportCreateBookmarks CreateBookmarks, Boolean DocStructureTags, Boolean BitmapMissingFonts, Boolean UseISO19005_1, Object& FixedFormatExtClassPtr)
в WordInPdf.Form1.btnConvert_Click(Object sender, EventArgs e) в c:documents and settingseesмои документыvisual studio 2010ProjectsWordInPdfWordInPdfForm1.cs:строка 66
в System.Windows.Forms.Control.OnClick(EventArgs e)
в System.Windows.Forms.Button.OnClick(EventArgs e)
в System.Windows.Forms.Button.OnMouseUp(MouseEventAr gs mevent)
в System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
в System.Windows.Forms.Control.WndProc(Message& m)
в System.Windows.Forms.ButtonBase.WndProc(Message& m)
в System.Windows.Forms.Button.WndProc(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.O nMessage(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.W ndProc(Message& m)
в System.Windows.Forms.NativeWindow.DebuggableCallba ck(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
в System.Windows.Forms.UnsafeNativeMethods.DispatchM essageW(MSG& msg)
в System.Windows.Forms.Application.ComponentManager. System.Windows.Forms.UnsafeNativeMethods.IMsoCompo nentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
в System.Windows.Forms.Application.ThreadContext.Run MessageLoopInner(Int32 reason, ApplicationContext context)
в System.Windows.Forms.Application.ThreadContext.Run MessageLoop(Int32 reason, ApplicationContext context)
в System.Windows.Forms.Application.Run(Form mainForm)
в WordInPdf.Program.Main() в c:documents and settingseesмои документыvisual studio 2010ProjectsWordInPdfWordInPdfProgram.cs:строк а 18
в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
в Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
в System.Threading.ThreadHelper.ThreadStart_Context( Object state)
в System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
в System.Threading.ThreadHelper.ThreadStart()



0



48 / 48 / 11

Регистрация: 13.08.2012

Сообщений: 97

13.05.2014, 15:25

4

Выложи свой проект или сделай новый с проблемой



0



192 / 199 / 82

Регистрация: 11.04.2013

Сообщений: 1,086

13.05.2014, 15:51

 [ТС]

5

прикрепил



0



Gul-79

48 / 48 / 11

Регистрация: 13.08.2012

Сообщений: 97

13.05.2014, 16:10

6

Переделал твой код

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void btnConvert_Click(object sender, EventArgs e)
       {
           string wordPath = FileNameTextBox.Text;
 
           var application = new Application { Visible = false };
           var doc = application.Documents.Open(wordPath);
 
           var pdfPath = Path.ChangeExtension(wordPath, "pdf");
 
           doc.ExportAsFixedFormat(pdfPath, WdExportFormat.wdExportFormatPDF,
                false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument);
 
           doc.Application.Quit();
       }



0



EVG-1980

192 / 199 / 82

Регистрация: 11.04.2013

Сообщений: 1,086

13.05.2014, 16:23

 [ТС]

7

Не помогло та же самая ошибка в office 2003 не пашет походу можешь прикрепить dll от офиса которые в папке reliase (debag)

Добавлено через 3 минуты
И еще

C#
1
var application = new Application { Visible = false };

application из какого пространства using System.Windows.Forms или using Microsoft.Office.Interop.Word?



0



48 / 48 / 11

Регистрация: 13.08.2012

Сообщений: 97

13.05.2014, 16:25

8

WordInPdf.rar

using Microsoft.Office.Interop.Word



0



192 / 199 / 82

Регистрация: 11.04.2013

Сообщений: 1,086

13.05.2014, 16:36

 [ТС]

9

Попытка чтения или записи в защищенную память. Это часто свидетельствует о том, что другая память повреждена.

Падлюка

У тебя нормально работает? ос и офис какой стоит?



0



48 / 48 / 11

Регистрация: 13.08.2012

Сообщений: 97

13.05.2014, 16:41

10

Работает нормально.
Винда 8.1.
Офис 2013
Да и на офисе 2007 должно все работать



0



EVG-1980

192 / 199 / 82

Регистрация: 11.04.2013

Сообщений: 1,086

13.05.2014, 16:59

 [ТС]

11

у меня 2003 и ExportAsFixedFormat там не пашет

Добавлено через 13 минут
Предупреждение 1

C#
1
doc.Application.Quit();

Неоднозначность между методом «Microsoft.Office.Interop.Word._Application.Quit(r ef object, ref object, ref object)» и «Microsoft.Office.Interop.Word.ApplicationEvents4_ Event.Quit», который методом не является. Используйте группу методов.

Не вкурю как поправить



0



48 / 48 / 11

Регистрация: 13.08.2012

Сообщений: 97

13.05.2014, 17:13

12

Это глюки библиотек ворда, в 2007 точно такой есть, можно не обращать внимание, работать код будет.



1



EVG-1980

192 / 199 / 82

Регистрация: 11.04.2013

Сообщений: 1,086

13.05.2014, 17:21

 [ТС]

13

Нашел как победить

C#
1
2
((_Application)doc).Quit();
Marshal.FinalReleaseComObject(doc);



0



48 / 48 / 11

Регистрация: 13.08.2012

Сообщений: 97

13.05.2014, 17:32

14

Не помогает, предупреждение так и весит



0



EVG-1980

192 / 199 / 82

Регистрация: 11.04.2013

Сообщений: 1,086

13.05.2014, 20:27

 [ТС]

15

вместо doc.Application.Quit(); напиши ((_Application)doc).Quit(); у меня убрало предупреждение

вопрос в другом как и какие экзепшены ловить если не установлен офис или если установлен 2003 офис как отловить System.AccessViolationException катчем оно не ловится почему то

Добавлено через 2 часа 13 минут
все поймал все что хотел

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  private void btnConvert_Click(object sender, EventArgs e)
       {
           var wordPath=FileNameTextBox.Text;
           Microsoft.Office.Interop.Word.Application application=null;
           Microsoft.Office.Interop.Word.Document doc = null;
           try
           {
               application = new Application { Visible = false };
               doc = application.Documents.Open(wordPath);
               var pdfPath = Path.ChangeExtension(wordPath, "pdf");
               doc.ExportAsFixedFormat(pdfPath, WdExportFormat.wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument);
           }
 
           catch (Exception ex) { MessageBox.Show(ex.Message); }
 
           finally
           {
               if (doc != null) { ((_Application)doc).Quit(false, null, null); doc = null; Marshal.FinalReleaseComObject(doc); }
               if (application != null) { ((_Application)application).Quit(); application = null;  Marshal.FinalReleaseComObject(application); }
           }
       }



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

13.05.2014, 20:27

Помогаю со студенческими работами здесь

Бесплатные либы для создания, редактирования PDF, DOCX, XLSX, XLS, DOC и конвертации их между собой
Существует ли бесплатная библиотека, которая позволяет делать все и сразу — создавать,…

Экспорт в pdf, doc
Возможно ли в Silverlight генерировать документы pdf, doc, тоесть знает ли ктонибудь готовые…

Как просматривать pdf и doc файлы?
Здравствуйте. Как в wpf c# сделать просмотр pdf, doc, docx файлов. Как это реализовать? Я нашел…

Конвертация Doc в PDF без использования Com.Interop
нужно конвертировать обычный вордовский файл в PDF. вопрос заключается в следующем,знает ли кто…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

15

Понравилась статья? Поделить с друзьями:
  • Interop word find range
  • Interop excel формат ячеек
  • Interop excel save file
  • Internet word of mouth
  • Internet word derived from