[英]DocumentFormat.OpenXml Adding an Image to a word doc
我正在使用openXml SDK創建一個簡單的Word文檔。 到目前為止,它正在工作。 現在如何將文件系統中的圖像添加到此文檔? 我不在乎它在文檔中的位置。 謝謝! 這是我到目前為止所擁有的。
string fileName = "proposal"+dealerId +Guid.NewGuid().ToString()+".doc";
string filePath = @"C:\DWSApplicationFiles\Word\" + fileName;
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document, true))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
//create the body
Body body = new Body();
DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
DocumentFormat.OpenXml.Wordprocessing.Run runParagraph = new DocumentFormat.OpenXml.Wordprocessing.Run();
DocumentFormat.OpenXml.Wordprocessing.Text text_paragraph = new DocumentFormat.OpenXml.Wordprocessing.Text("This is a test");
runParagraph.Append(text_paragraph);
p.Append(runParagraph);
body.Append(p);
mainPart.Document.Append(body);
mainPart.Document.Save();
}
這是一種比上面msdn頁面中描述的方法更簡單的方法,此代碼在C ++ / CLI中,但是您當然可以在C#中編寫等效的方法
WordprocessingDocument^ doc = WordprocessingDocument::Open(doc_name, true);
FileStream^ img_fs = gcnew FileStream(image_path, FileMode::Open);
ImagePart^ image_part = doc->MainDocumentPart->AddImagePart(ImagePartType::Jpeg);
image_part->FeedData(img_fs);
Run^ img_run = doc->MainDocumentPart->Document->Body->AppendChild(gcnew Paragraph())->AppendChild(gcnew Run());
Vml::ImageData^ img_data = img_run->AppendChild(gcnew Picture())->AppendChild(gcnew Vml::Shape())->AppendChild(gcnew Vml::ImageData());
img_data->RelationshipId = doc->MainDocumentPart->GetIdOfPart(image_part);
doc->Close();
該代碼對我有用 : http : //msdn.microsoft.com/en-us/library/bb497430.aspx
您的代碼將圖像添加到docx包中,但是要在文檔中看到它,您必須在document.xml中聲明它,即將其鏈接到您的物理圖像。 這就是為什么您必須編寫msdn鏈接中列出的long函數的原因。
我的問題是如何為圖片添加效果(編輯,裁剪,背景去除)。 如果您知道該怎么做,我會很感激您的幫助
如何:使用Open XML API將圖像部件添加到Office Open XML包中
http://msdn.microsoft.com/zh-CN/library/bb497430(v=office.12).aspx
public static void AddImagePart(string document, string fileName)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.