明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
  博客园  :: 首页  :: 管理

Spire.Doc基本操作

Posted on 2021-11-25 11:26  且行且思  阅读(3655)  评论(1编辑  收藏  举报

Spire.Doc基本操作,你会了吗?

1. 问:如何从word文档中获取文本?

答:您可以调用方法method document.GetText()来执行此操作。完整代码:

1
2
3
4
5
6
7
Document document = new Document();
document.LoadFromFile(@"..\..\test.docx");
using (StreamWriter sw = File.CreateText("output.txt"))
 {
 sw.Write(document.GetText());
 }
 <br><br>

2. 问:如何插入具有指定高度和宽度的图像?

答:您可以设置DocPicture的属性高度和宽度来调整图像大小。完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
Document document = new Document();
document.LoadFromFile("sample.docx", FileFormat.Docx);
Image image = Image.FromFile("image.jpg");
 
//specify the paragraph
Paragraph paragraph = document.Sections[0].Paragraphs[2];
DocPicture picture = paragraph.AppendPicture(image);
 
//resize the image
picture.Height = picture.Height * 0.8f;
picture.Width = picture.Width * 0.8f;
document.SaveToFile("result.docx", FileFormat.Docx);<br><br>

3. 问:如何对齐word文档中的文本?

答:请设置段落的属性Horizo​​ntalAlignment以对齐文本。完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Document document = new Document();
document.LoadFromFile("sample.docx");
 
//set paragraph1 to align left
Paragraph paragraph1 = document.Sections[0].Paragraphs[0];
paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Left;
 
//set paragraph2 to align center
Paragraph paragraph2 = document.Sections[0].Paragraphs[1];
paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Center;
 
//set paragraph3 to align right
Paragraph paragraph3 = document.Sections[0].Paragraphs[2];
paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Right;
document.SaveToFile("result.docx");

4. 问:如何更改现有书签上的文字?

答:您可以使用BookmarksNavigator来查找指定的书签。然后请调用ReplaceBookmarkContent方法替换书签上的文本。完整代码:

1
2
3
4
5
6
7
8
Document document = new Document();
document.LoadFromFile("sample.doc");
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
bookmarkNavigator.MoveToBookmark("mybookmark");
 
//replace text on bookmarks
bookmarkNavigator.ReplaceBookmarkContent("new context", false);
document.SaveToFile("result.doc", FileFormat.Doc);
1
 

5. 问:如何将word转换为html?

答:您可以使用指定的文件格式HTML调用SaveToFile方法将word文档转换为html。完整代码:

1
2
3
4
5
6
Document document = new Document();
document.LoadFromFile("sample.doc");
 
//save word document as html file
document.SaveToFile("result.html", FileFormat.Html);
document.Close();

6. 问:如何将html转换为word文档?

答:请调用LoadFromFile方法加载html文件。然后调用SaveToFile方法将html转换为word文档。完整代码:

1
2
3
4
5
6
Document document = new Document();
 
document.LoadFromFile("sample.html", FileFormat.Html, XHTMLValidationType.None);
//save html as word document
document.SaveToFile("result.doc");
document.Close();

7. 如何将word2007转换为word2003?

答:只需使用指定的文件格式doc调用SaveToFile方法即可将word2007转换为word2003。完整代码:

1
2
3
4
5
Document document = new Document("word2007.docx");
 
//convert word2007 to word2003
document.SaveToFile("word2003.doc", FileFormat.Doc);
document.Close();

8. 问:如何替换和删除Word文档中的页眉或页脚?

答:请使用Section获取页眉或页脚。您可以调用替换方法来替换标题并调用Clear方法以删除Word文档的页眉或页脚。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Document document = new Document();
Section section = document.AddSection();
 
//add a header
HeaderFooter header = section.HeadersFooters.Header;
Paragraph headerParagraph = header.AddParagraph();
TextRange text = headerParagraph.AppendText("Demo of Spire.Doc");
text.CharacterFormat.TextColor = Color.Blue;
document.SaveToFile("DocWithHeader.doc");
 
//replace the header
headerParagraph.Replace("Demo", "replaceText", true, true);
document.SaveToFile("DocHeaderReplace.doc");
document.LoadFromFile("DocWithHeader.doc");
 
//delete the heater
document.Sections[0].HeadersFooters.Header.Paragraphs.Clear();
document.SaveToFile("DocHeaderDelete.doc");<br><br>

9. 问:如何合并word文档?

答:请调用克隆方法复制一节。然后调用Add方法将该部分的副本添加到指定的文档。完整代码:

1
2
3
4
5
6
7
8
9
10
11
Document document1 = new Document();
document1.LoadFromFile("merge1.docx");
Document document2 = new Document();
document2.LoadFromFile("merge2.docx");
 
//add sections from document1 to document2
foreach (Section sec in document2.Sections)
{
    document1.Sections.Add(sec.Clone());
}
document1.SaveToFile("result.docx");
1
 

10. 问:如何遍历word文档中表格的单元格?

答:行是表中行的集合,单元是行中单元的集合。所以你可以用两个循环来遍历表格的单元格。完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
Document document = new Document();
document.LoadFromFile("sample.docx");
Spire.Doc.Interface.ITable table = document.Sections[0].Tables[0];
int i=0;
 
//traverse the cells
foreach (TableRow row in table.Rows)
{
    foreach (TableCell cell in row.Cells)
    {
        i++;
    }
}<br><br>

11. 问:如何设置阴影文字?

答:您只需设置TextRange的属性IsShadow即可。完整代码:

1
2
3
4
5
6
7
8
9
Document document = new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
TextRange HText = paragraph.AppendText("this is a test!");
 
//set the property IsShadow
HText.CharacterFormat.IsShadow = true;
HText.CharacterFormat.FontSize = 80;
document.SaveToFile("result.doc");<br><br>

12. 问:如何在Word中插入行号?

答:您需要设置节的属性LineNumberingRestartMode,LineNumberingStep,LineNumberingStartValue以在Word文档中插入行号。完整代码:

1
2
3
4
5
6
7
8
9
10
Document document = new Document();
Section section = document.AddSection();
 
//insert line numbers
section.PageSetup.LineNumberingRestartMode = LineNumberingRestartMode.RestartPage;
section.PageSetup.LineNumberingStep = 1;
section.PageSetup.LineNumberingStartValue = 1;
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText("As an independent Word .NET component, Spire.Doc for .NET doesn't need Microsoft Word to be installed on the machine. However, it can incorporate Microsoft Word document creation capabilities into any developers .NET applications.");
document.SaveToFile("result.doc");
1
 

13. 问:如何使图像周围的文字?

答:您需要设置图片的属性TextWrappingStyle和ShapeHorizo​​ntalAlignment。完整代码:

1
2
3
4
5
6
7
8
9
Document document = new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
string str = "As an independent Word .NET component, Spire.Doc for .NET doesn't need Microsoft Word to be installed on the machine. However, it can incorporate Microsoft Word document creation capabilities into any developers.NET applications.As an independent Word .NET component, Spire.Doc for .NET doesn't need Microsoft Word to be installed on the machine. However, it can incorporate Microsoft Word document creation capabilities into any developers’.NET applications.";
paragraph.AppendText(str);
DocPicture picture = paragraph.AppendPicture(Image.FromFile("logo.png"));
picture.TextWrappingStyle = TextWrappingStyle.Tight;
picture.HorizontalAlignment = ShapeHorizontalAlignment.Center;
document.SaveToFile("result.doc");<br><br>
1
 

14. 问:如何编辑Word文档中的现有表?

答:使用Section获取表格,您可以编辑单元格中的文本,并且可以将新行插入到表格中。完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Document doc = new Document("sample.docx");
Section section = doc.Sections[0];
ITable table = section.Tables[0];
 
//edit text in a cell
TableCell cell1 = table.Rows[1].Cells[1];
Paragraph p1 = cell1.Paragraphs[0];
p1.Text = "abc";
 
TableCell cell2 = table.Rows[1].Cells[2];
Paragraph p2 = cell2.Paragraphs[0];
p2.Items.Clear();
p2.AppendText("def");
 
TableCell cell3 = table.Rows[1].Cells[3];
Paragraph p3 = cell3.Paragraphs[0];
(p3.Items[0] as TextRange).Text = "hij";
 
//insert new row
TableRow newRow = table.AddRow(true, true);
foreach (TableCell cell in newRow.Cells)
{
    cell.AddParagraph().AppendText("new row");
}
doc.SaveToFile("result.doc");<br><br><br>

15. 问:如何设置超链接的格式不带下划线?

答:请设置超链接字段的textRange节点来格式化超链接。完整代码:

1
2
3
4
5
6
7
8
Document document = new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
Field hyperlink = paragraph.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);
TextRange text = hyperlink.NextSibling.NextSibling as TextRange;
text.CharacterFormat.Bold = true;
text.CharacterFormat.UnderlineStyle = UnderlineStyle.None;
document.SaveToFile("result.doc");

16. 问:如何设置word文档只读?

答:请调用Protect方法设置ProtectionType。完整代码:

1
2
3
4
Document document = new Document();
document.LoadFromFile("sample.docx");
document.Protect(ProtectionType.AllowOnlyReading);
document.SaveToFile("result.doc");<br><br>

添加多行文字水印到 Word 文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
 
namespace WordWatermark
{
    class Program
    {
        static void Main(string[] args)
        {
            //加载示例文档
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx");
 
            //添加艺术字并设置大小
            ShapeObject shape = new ShapeObject(doc,ShapeType.TextPlainText);
            shape.Width = 60;
            shape.Height = 20;
 
            //设置艺术字文本内容、位置及样式
            shape.VerticalPosition = 30;
            shape.HorizontalPosition = 20;
            shape.Rotation = 315;
            shape.WordArt.Text = "内部使用";
 
            shape.FillColor = System.Drawing.Color.Red;
            shape.StrokeColor = System.Drawing.Color.Gray;
 
            Section section;
            HeaderFooter header;
           for (int n = 0; n < doc.Sections.Count; n++) <br>{ <br>section = doc.Sections[n]; <br>//获取section的页眉 <br>header = section.HeadersFooters.Header; <br>Paragraph paragraph1; <br>for (int i = 0; i < 3; i++) <br>{ <br>//添加段落到页眉 <br>paragraph1 = header.AddParagraph(); <br>for (int j = 0; j < 4; j++) <br>{ <br>//复制艺术字并设置多行多列位置 <br>shape = (ShapeObject)shape.Clone(); <br>shape.VerticalPosition = 50 + 150 * i; <br>shape.HorizontalPosition=20 + 160 * j; <br>paragraph1.ChildObjects.Add(shape); } <br>} <br>} <br>//保存文档 <br>doc.SaveToFile("result.docx", FileFormat.Docx2013); <br>System.Diagnostics.Process.Start("result.docx"); <br>} <br>} <br>}

C# 修改 Word 文档中图片的大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//加载Word文档
Document document = new Document("Input.docx");
//获取第一个section
Section section = document.Sections[0];
//获取第一个段落
Paragraph paragraph = section.Paragraphs[0];
//调整段落中图片的大小 
foreach (DocumentObject docObj in paragraph.ChildObjects)
{
    if (docObj is DocPicture)
    {
        DocPicture picture = docObj as DocPicture;
        picture.Width = 50f;
        picture.Height = 50f;
    }
}
//保存文档 
document.SaveToFile("ResizeImages.docx");<br><br>

C# 设置Word页面大小和页边距

using Spire.Doc;

using Spire.Doc.Documents;

 

namespace SetPageSize_Doc

{

    class Program

    {

        static void Main(string[] args)

        {

            //实例化一个Document对象

            Document doc = new Document();

            //载入测试的Word文档

            doc.LoadFromFile("test.docx");

            //获取第一个Section对象

            Section sec = doc.Sections[0];

 

            //设置纸张大小为信纸

            sec.PageSetup.PageSize = PageSize.Letter;

 

            //分别设置四个方向的页边距

            sec.PageSetup.Margins.Top = 20f;

            sec.PageSetup.Margins.Left = 30f;

            sec.PageSetup.Margins.Bottom = 20f;

            sec.PageSetup.Margins.Right = 30f;

            //把纸张方向设置为横向

            sec.PageSetup.Orientation = PageOrientation.Landscape;

 

            //保存并打开文档

            doc.SaveToFile("result.docx", FileFormat.Docx2010);

            System.Diagnostics.Process.Start("result.docx");

        }

    }

}

 

C#代码示例(供参考)

【示例1】添加PDF文本水印


作者:EiceblueSpire
链接:https://www.imooc.com/article/284363
来源:慕课网
本文原创发布于慕课网 ,转载请注明出处,谢谢合作
using Spire.Pdf;
using Spire.Pdf.Annotations;
using Spire.Pdf.Annotations.Appearance;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;
namespace TextWatermark
 {    
    class Program    
    {        
         static void Main(string[] args)
         {
          //创建PdfDocument对象            
          PdfDocument pdf = new PdfDocument();
          //加载现有PDF文档
          pdf.LoadFromFile("sample.pdf");             
          //创建True Type字体            
          PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", 20f), true);
          //水印文字            
          string text = "版权所有\n侵权必究";             
          //测量文字所占的位置大小,即高宽            
          SizeF fontSize = font.MeasureString(text);             
          //计算两个偏移量            
          float offset1 = (float)(fontSize.Width * System.Math.Sqrt(2) / 4);            
          float offset2 = (float)(fontSize.Height * System.Math.Sqrt(2) / 4);
          //遍历文档每一页            
          foreach (PdfPageBase page in pdf.Pages)            
          {                
             //创建PdfTilingBrush对象                
              PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.Size.Width / 2, page.Canvas.Size.Height / 2));
             //设置画刷透明度                
              brush.Graphics.SetTransparency(0.8f);                 
             //将画刷中坐标系向右下平移                
              brush.Graphics.TranslateTransform(brush.Size.Width / 2 - offset1 - offset2, brush.Size.Height / 2 + offset1 - offset2);
             //将坐标系逆时针旋转45度                
              brush.Graphics.RotateTransform(-45);                 
             //在画刷上绘制文本                
              brush.Graphics.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);                 
             //在PDF页面绘制跟页面一样大小的矩形,并使用定义的画刷填充                
              page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.Size));            
            }             
          //保存文档            
          pdf.SaveToFile("output.pdf");            
          System.Diagnostics.Process.Start("output.pdf");                 
        }    
     }
  }

完成代码后,调试运行程序,生成文档,如下:

https://img3.sycdn.imooc.com/5ca44aab000117bb06170357.jpg