Skip to content

Instantly share code, notes, and snippets.

@istupakov
Last active November 17, 2015 21:41
Show Gist options
  • Save istupakov/6b1026168721393ce8c9 to your computer and use it in GitHub Desktop.
Save istupakov/6b1026168721393ce8c9 to your computer and use it in GitHub Desktop.
Export images from Word or Excel file to separate pdf files.
using System;
using System.IO;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
namespace MsOfficeImagesToPdf
{
class Converter : IDisposable
{
Word.Application word = new Word.Application();
Excel.Application excel = new Excel.Application();
string filename;
int counter;
string GetNextFilename()
{
return Path.ChangeExtension($"{Path.GetFileNameWithoutExtension(filename)} pic{counter++:D3}", "pdf");
}
void Save(float width, float height)
{
var newDoc = word.Documents.Add();
var coef = width > 482 ? 17 * 28.3464567f / width : 1;
width *= coef;
height *= coef;
try
{
var range = newDoc.Range();
var page = range.PageSetup;
page.BottomMargin = 0;
page.TopMargin = 0;
page.LeftMargin = 0;
page.RightMargin = 0;
page.PageWidth = width;
page.PageHeight = height;
range.Paste();
if (range.InlineShapes.Count > 0)
range.InlineShapes[1].ConvertToShape();
range.ShapeRange.Top = 0;
range.ShapeRange.Left = 0;
range.ShapeRange.Width = width;
range.ShapeRange.Height = height;
var name = GetNextFilename();
Console.WriteLine($"{name} - {width}x{height}");
newDoc.SaveAs(Path.Combine(Environment.CurrentDirectory, name), Word.WdSaveFormat.wdFormatPDF);
}
finally
{
newDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
}
}
void ProcessWordDoc(string filename)
{
var doc = word.Documents.Open(filename, ReadOnly: true);
var shapes = doc.InlineShapes.OfType<Word.InlineShape>().Select(s => s.ConvertToShape());
foreach (var shape in doc.Shapes.OfType<Word.Shape>().Concat(shapes))
{
shape.Select();
word.Selection.Copy();
Save(shape.Width, shape.Height);
}
doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
}
void ProcessExcelBook(string filename)
{
var book = excel.Workbooks.Open(filename, ReadOnly: true);
foreach (var sheet in book.Worksheets.OfType<Excel.Worksheet>())
{
foreach (var shape in sheet.Shapes.OfType<Excel.Shape>())
{
shape.CopyPicture();
Save(shape.Width, shape.Height);
}
}
book.Close(Excel.XlSaveAction.xlDoNotSaveChanges);
}
public void Dispose()
{
excel.Quit();
word.Quit();
}
public void Convert(string filename)
{
this.filename = filename;
this.counter = 1;
switch (Path.GetExtension(filename))
{
case ".doc":
case ".docx":
ProcessWordDoc(filename);
break;
case ".xls":
case ".xlsx":
ProcessExcelBook(filename);
break;
}
}
}
class Program
{
static void Main(string[] args)
{
using (var converter = new Converter())
{
converter.Convert(Path.Combine(Environment.CurrentDirectory, args[0]));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment