我有一个应用程序,它将打印一个.docx文件,它有一个文本框形状与文本。在它里面,有一些单词需要加粗。
例如,文本的一部分是"...representando a empresa M&A,o presente...“只有“并购”才需要大胆。
然而,我不确定我该如何做到这一点。我已经搜索了SO,以及其他像MSDN之类的网站,但都没有提供解决方案。有人能帮帮我吗?
编辑:我正在使用Interop来实现这一点。到目前为止,我所做的代码如下:
// opens word app
wordApp = new Microsoft.Office.Interop.Word.Application();
wordApp.Visible = false;
// print dialog for settings input
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() == DialogResult.OK)
{
wordApp.ActivePrinter = pd.PrinterSettings.PrinterName;
// opens the document
Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(filePath);
// iterates through each shape in the file
foreach (Microsoft.Office.Interop.Word.Shape shape in doc.Shapes)
{
string shapeName = shape.Name;
// checks whether the shape is a Text Box
if (shapeName.StartsWith("Text Box"))
{
string shapeText = shape.TextFrame.ContainingRange.Text;
// checks whether the shape is the one I want to modify
// side note: there are more shapes in the file, so I specify it
if (shapeText.StartsWith("Concedemos"))
{
// erases the text, and sets it to a string
shape.TextFrame.ContainingRange.Text = "";
shape.TextFrame.ContainingRange.Text = "textSample";
}
}
}
// prints the file
wordApp.ActiveDocument.PrintOut();
}
// quits the app
wordApp.Quit();
wordApp = null;
提前感谢!
发布于 2019-05-26 00:11:31
下面的代码片段演示了如何遍历Word文档中的所有形状,检查它是否是以所需字符串开头的文本框(绘图元素),然后在文本框中搜索要加粗的术语。
Shape.Type
以确定它是否是文本框。Shape.Type
是一个Office枚举(因为Shape
对象对于许多Office应用程序都是通用的)。因此,Word的Range.Find
功能通常是最好的方法,所以Word挑选文本并格式化它。它可以查找和替换格式,以及字符串值。(提示:当着手一个需要这类东西的项目时,最好在Word UI中的对话框(Ctrl+H)中进行测试,以找出parameters.)Find.Execute
的所有参数的用途,请参阅帮助或查看智能感知(或两者的组合)。对于本例,重要的是要注意,为了格式化目标文本,没有指定Replacement.Text
。
foreach (Microsoft.Office.Interop.Word.Shape shape in doc.Shapes)
{
Office.MsoShapeType shapeType = shape.Type;
// checks whether the shape is a Text Box
if (shapeType == Office.MsoShapeType.msoTextBox)
{
// checks whether the shape is the one I want to modify
// side note: there are more shapes in the file, so I specify it
if (shapeText.StartsWith("Concedemos"))
{
string textToBold = "M&A";
Word.Range rngTextBox = shape.TextFrame.TextRange;
Word.Find rngFind = rngTextBox.Find;
rngFind.Text = textToBold;
rngFind.Replacement.Font.Bold = -1;
object oFindStop = Word.WdFindWrap.wdFindStop;
object oTrue = true;
object oReplaceAll = Word.WdReplace.wdReplaceAll;
object missing = System.Type.Missing;
rngFind.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref oFindStop, ref oTrue, ref missing, ref oReplaceAll,
ref missing, ref missing, ref missing, ref missing);
}
}
https://stackoverflow.com/questions/56279713
复制相似问题