示列1:
在C#中操作word,使用aspose.words这个控件是很方便的,也能用它来导出嵌入在word文档中的OLE对象(gif,jpg,png,txt,html等内容)。
代码如下
public void ExtractImg()
{
Document doc = new Document(@ "c:\test.doc");
//取得对象集合
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
int i = 0;
foreach (Shape shape in shapes)
{
if (shape.OleFormat != null)
{
//生成文件名
string name = @ "c:\obj_" + shape.OleFormat.ProgId + i.ToString();
//判断OLE格式是否为Package(包)
if (shape.OleFormat.ProgId == "Package")
{
MemoryStream strm = new MemoryStream();
shape.OleFormat.Save(strm);
try
{
//保存图片
Bitmap img = (Bitmap)Bitmap.FromStream(strm);
img.Save(name + ".png", ImageFormat.Png);
}
catch
{
Stream file = new FileStream(name + ".object", FileMode.Create);
strm.WriteTo(file);
}
}
i++;
}
}
}
示列2:
读取文档中图片并保存的方法如下:
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true, false);
foreach (Shape shape in shapes)
{
if (shape.IsImage)
{
shape.Height = 100;
shape.ImageData.Save("");
shape.Remove();
}
}
插入图片的方法如下:
DocumentBuilder builder = new DocumentBuilder();
builder.InsertImage(" ")
示例3:
// Load the word document Document wordDocument = new Document("Invitation.doc"); // get all the shapes NodeCollection shapes = wordDocument.GetChildNodes(NodeType.Shape, true, false); // loop through all the shapes foreach (Shape shape in shapes) { // check if it has an image if (shape.HasImage) { // save the image in memory stream MemoryStream imgStream = new MemoryStream(); shape.ImageData.Save(imgStream); // recognize the barcode from the image stream above BarCodeReader reader = new BarCodeReader(new Bitmap(imgStream), BarCodeReadType.Code39Standard); while(reader.Read()) { Console.WriteLine("Codetext found: "+ reader.GetCodeText()); } // close the reader reader.Close(); }
其它例子:
我要做一个试题导入程序,现在使用aspose.words能获取表格中的文本,图片,但就是不知道怎么获得图片在文本中的位置。想通过这个来生成一个html字符串,代码如下:
private void ViewNodeListImg() { Document doc = new Document("E:\\3-学习与培训\\2-程序学习\\读取Word图片项目\\WordImgTest\\WordImgTest\\upload\\test.doc"); Aspose.Words.Tables.Table table = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true); string MyDir = "E:\\3-学习与培训\\2-程序学习\\读取Word图片项目\\WordImgTest\\WordImgTest\\upload\\img\\"; int imageIndex = 0; string str = ""; str += "<table>"; // Iterate through all rows in the table. foreach (Row row in table.Rows) { str += "<tr>"; // Iterate through all cells in the table. foreach (Cell cell in row.Cells) { str += "<td>"; str +="<p>"+cell.Paragraphs.ToArray()[0].ToTxt()+"</p>"; NodeCollection shapes = cell.GetChildNodes(NodeType.Shape, true, false); foreach (Shape shape in shapes) { //str += shape.Range; if (shape.HasImage) { string imageFileName = string.Format( "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType)); shape.ImageData.Save(MyDir + imageFileName); imageIndex++; } } str += "</td>"; } str += "</tr>"; } Response.Write(str); }