[英]Find Pictures in a Word Document programmatically
問題:-
在最近工作中的品牌重塑練習中,所有 Word 文檔(保存為 RTF 文件))
我有大小為 2、3 甚至 4MB 的 Word 文檔。
查看文檔中的圖片,我注意到有些縮小到 48%、70%、88% 等等。 如果我從文檔中剪下圖像,將其粘貼到 Paint.NET 中,調整其大小,將其粘貼回文檔並按照原始位置進行定位,我可以將文檔的大小縮小到小於 1/10手動捏造的。
我想以編程方式處理 1150 個 Word 文檔並在其中找到縮放的圖片。 然后我想把圖片拉出來,調整它們的大小,然后把它們放回去替換手動添加的圖片。 節省磁盤空間。
我在導航 Word 對象模型和以編程方式查找圖片時遇到困難。
MSDN上的這個網頁說你可以像這樣添加它們
this.Application.Selection.InlineShapes.AddPicture(@"C:\SamplePicture.jpg");
所以我認為使用 InlineShapes 集合可以讓我訪問文檔中的圖片集合。
我已經聲明了互操作。
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop;
using Microsoft.Office;
我打開 Word 應用程序,並像這樣記錄(這有效)
private void OpenWordApplication()
{
_WordApp = new Microsoft.Office.Interop.Word.Application();
if (chkVisibleWord.CheckState == CheckState.Checked) {
_WordApp.Visible = true;
}
else
{
_WordApp.Visible = false;
}
}
private void OpenTheDocument(string DocumentPath)
{
_WordDoc = _WordApp.Documents.Open(DocumentPath);
changesMade = false;
}
當我試圖在 InlineShapes 中找到 eh 圖片時,我似乎無法找到它們。
_WordApp.Selection.HomeKey(WdUnits.wdStory);
int picCount = _WordApp.ActiveDocument.InlineShapes.Count;
MessageBox.Show(string.Format("There are {0} images in this document", picCount));
我收到一個消息框,說計數為零。
注意:該應用程序在 Word 中打開文檔就好了。 它根據我在表單上選中的復選框對文檔執行其他操作,對我來說問題似乎在於訪問 InlineShapes 集合。
任何指針。 我感謝您到目前為止的關注?
提前致謝
我們最終的解決方案是找一個測試人員,他會使用 Microsoft Word、一張紙、一支鉛筆和 Paint.Net 應用程序。
測試人員使用鉛筆和紙標出圖像的尺寸和位置,並使用 Paint.Net 調整圖像大小。
我知道它並沒有像我最初打算的那樣以編程方式處理文檔/圖像,但是我們有一個截止日期來完成該過程,有時作為開發人員,當您認為手動處理是正確的時,您必須撥打電話要做的事。
嘗試:
foreach (Microsoft.Office.Interop.Word.Shape s in wordApp.ActiveDocument.Shapes)
{
...
}
此代碼將查找文檔中的所有內嵌圖片。 這些確實是內聯形狀。 所以不確定 OP 代碼的問題是什么。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;
namespace OfficeBench
{
class Program
{
static void Main(string[] args)
{
Application app = new Application();
Document doc = app.Documents.Open(@"c:\scratch\so\4pictures.docx");
if (doc != null)
{
Console.WriteLine($"Number in in-line shapes = {doc.InlineShapes.Count}");
foreach (InlineShape shape in doc.InlineShapes)
{
Console.WriteLine($"Shape (width,height) = ({shape.Width},{shape.Height})");
Console.WriteLine($"Shape type = {shape.Type}");
Console.WriteLine();
if (shape.Type == WdInlineShapeType.wdInlineShapePicture)
{
// ...
}
}
doc.Close();
}
else
{
Console.WriteLine("Error - Unable to open document.");
}
}
}
}
這會產生輸出...
Number in in-line shapes = 4
Shape (width,height) = (293.25,164.75)
Shape type = wdInlineShapePicture
Shape (width,height) = (412.5,231.75)
Shape type = wdInlineShapePicture
Shape (width,height) = (226.9,127.5)
Shape type = wdInlineShapePicture
Shape (width,height) = (222.75,125.1)
Shape type = wdInlineShapePicture
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.