当前位置:网站首页>use Asponse.Words Working with word templates
use Asponse.Words Working with word templates
2020-11-06 01:23:00 【itread01】
One . Customer needs
Recently received a project , After initial communication with customers , The requirements described by customers also sound very simple , At present, customers need to be in Excel Input data , And then copy the data to multiple Word In many places , Except for individual values , You also need to copy forms and pictures , The customer thinks that this operation is easy to make mistakes , Second, the workload of repeated operation is too large . After a preliminary understanding of the user's needs , The core function of knowing the customer's needs is in Word Fill in the source of information , The sources that need to be filled in include text , Tables, pictures, etc , This article takes this as the starting point , It focuses on how to use Word Use in “ Domain ” To fill in external data .
Two . Plug in selection
At the moment Word etc. Office The control element of the document type , Microsoft comes with Com There are too many problems with components , One of the more troublesome problems is part of Com Components need to be registered , And if the client and the development computer use Com Component version inconsistency , There will be all kinds of problems , So I chose Asponse.words Plug in , The software is a charge plug-in , Specific charging standards can be viewed on the official website .
3、 ... and . Template making
utilize Asponse Fill in the data , In fact, the code is not difficult , The core job is to be in Word Set the mark in the template , That is, you need to let the program know where to fill in the data , At present, there are two ways to mark , One is to use bookmarks , One is to use the domain . At present, most cases on the Internet use bookmarks , But in the course of my actual development , I suggest you use “ Domain ”, Instead of using Bookmarks , The reasons are as follows :
1. Bookmarks cannot be added repeatedly , For example, I need to insert the data source in the first blank “ full name ”, Insert... In the last signature “ full name ”, Use this time “ Domain ” You can insert it in both places “ full name ” Domain , But if you use bookmarks , You need to set different bookmark names , When generating data sources, it will increase the workload
2. Bookmarks can't be displayed directly in the file , If you insert more Bookmarks , It's easy to cause confusion
Besides , It should be noted that , Make a bookmark or “ Domain " Be sure to use Word instead of WPS Make , Because one of the problems we've found is , Use WPS Make a bookmark or ” Domain “, A blank line will be added automatically after filling the data , This could be WPS And Word The internal mechanism is different ; There's another trick , Use... In documents Alt+F9, You can view the various domain codes of the template , As shown in the figure below :
Four . Insert bookmark / Domain
1. Insert bookmark
2. Insert field ( Insert -> File parts -> Domain , Choice "MergeField")
5、 ... and . Implementation code
1. Get the file
Aspose.Words.Document doc = new Aspose.Words.Document(filePath);
Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);
2. utilize word Template filling information
List<string> filedsValueList = new List<string>();
string[] filedsName =doc.MailMerge.GetFieldNames();// Get all the fields in the file
for (int i = 0; i < filedsName.Length; i++)
{
if (dataTable.Columns.Contains(filedsName[i]))
{
filedsValueList.Add(dataTable.Rows[0][filedsName[i]].ToString());
}
else
{
filedsValueList.Add("");
}
}
// The core code is actually this sentence , All of the above are organization sources
// The arguments are two arrays , The first array is all of the ” Domain “ The name of , The second is the value of the corresponding field
doc.MailMerge.Execute(filedsName, filedsValueList.ToArray());
3. Insert a picture
You don't need special code to insert images , It's about the need for Word Make special settings for the fields in the template , The way to set it is :
In the dialog box that pops up , hold ” Domain “ Add... Before the name "Image:", As shown in the figure below :
After setting it up , Just set the value of this field to the path of the image , The picture can be displayed in the document , If you need to control the size of the image in your code , Call back events that need to be processed for file binding images , The code is as follows :
doc.MailMerge.FieldMergingCallback = new HandleMerFieldInsert();
4. Set the image size
stay Asponse In the methods provided directly , There is no way to change the size of the picture , But it can be rewritten Asponse Of IFieldMergingCallback Class , Used to set the image size
class HandleMerFieldInsert : IFieldMergingCallback
{
// Word processing
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
}
// Image processing
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
Document doc = args.Document;
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField(args.FieldName);
Shape shapeImage = builder.InsertImage(args.FieldValue.ToString());
// Set x,y Coordinates and height and width .
shapeImage .Left = 0;
shapeImage .Top = 0;
shapeImage .Width = 50;
shapeImage .Height = 25;
}
}
5. Fill in the form
Fill in the form information , You need to set the starting position of the table binding data in the template , Then set the column name in the data source in each column , The specific steps are shown in the figure below :
The starting mark of the table data source is ”TableStart“, The end is marked with "TableEnd", After setting the start and end tags of the table data source , In each column, you can set the column name that needs to be bound in each column , The set data source is shown in the figure below :
Through Alt+F9 You can see the code of various fields set up , As shown in the figure below :
After setting the fields of the table , Fill in the data source with the following code :
dt.TableName = "UserInfo";// The table name here must be the same as the start and end source names of the table in the template
doc.MailMerge.ExecuteWithRegions(dt);
6. Delete the table and its corresponding place holder
Use Asponse The operation of deleting is relatively complicated , The existing business needs to delete a table in the template , But the problem is , After deleting the form , The place holder on the page where the form is located is still , Will result in a blank page in the generated file , So delete similar tables , When pictures are such elements , You also need to delete the corresponding paragraph placeholder
NodeCollection nodeCollection = doc.GetChildNodes(NodeType.Table, true);// Get all the forms
foreach (Table table in nodeCollection)
{
if (table.GetText().Contains("AAAAAA") && table.GetText().Contains("BBBBBB"))//To Do: Here we can determine whether it is a deleted form by getting the contents of the table , There should be a better way
{
Paragraph paragraph = (Paragraph)table.PreviousSibling;
paragraph.Remove();// Delete the paragraph
table.Remove();// Delete the table
}
}
7. Store the password PDF
Aspose.Words.Saving.PdfSaveOptions saveOption = new Aspose.Words.Saving.PdfSaveOptions();
saveOption.SaveFormat = Aspose.Words.SaveFormat.Pdf;
PdfEncryptionDetails encryptionDetails = new PdfEncryptionDetails(pdfPwd, string.Empty, PdfEncryptionAlgorithm.RC4_128);
encryptionDetails.Permissions = PdfPermissions.AllowAll;
saveOption.EncryptionDetails = encryptionDetails;
doc.Save(fullfilepath + ".pdf", saveOption);
8. Delete unassigned “ Domain ”
doc.MailMerge.DeleteFields();
At the end
thus ,Asponse The general methods of using templates to process data are summarized , For direct use Asponse Methods , stay Word In the form of hard coding, it is recommended that you do not use it as a last resort , Because adding a table requires controlling the style of the table itself , You also need to control the style of cells , And for complex documents , Positioning tables can also make it more difficult .
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
边栏推荐
- From zero learning artificial intelligence, open the road of career planning!
- Leetcode's ransom letter
- High availability cluster deployment of jumpserver: (6) deployment of SSH agent module Koko and implementation of system service management
- What is the difference between data scientists and machine learning engineers? - kdnuggets
- I'm afraid that the spread sequence calculation of arbitrage strategy is not as simple as you think
- 从海外进军中国,Rancher要执容器云市场牛耳 | 爱分析调研
- 6.2 handleradapter adapter processor (in-depth analysis of SSM and project practice)
- Serilog原始碼解析——使用方法
- The road of C + + Learning: from introduction to mastery
- 5.4 static resource mapping
猜你喜欢

ES6学习笔记(五):轻松了解ES6的内置扩展对象

从海外进军中国,Rancher要执容器云市场牛耳 | 爱分析调研

Subordination judgment in structured data

Do not understand UML class diagram? Take a look at this edition of rural love class diagram, a learn!

一篇文章教会你使用HTML5 SVG 标签

阿里云Q2营收破纪录背后,云的打开方式正在重塑

容联完成1.25亿美元F轮融资

Filecoin主网上线以来Filecoin矿机扇区密封到底是什么意思

Aprelu: cross border application, adaptive relu | IEEE tie 2020 for machine fault detection

一篇文章带你了解SVG 渐变知识
随机推荐
JVM memory area and garbage collection
Using consult to realize service discovery: instance ID customization
Examples of unconventional aggregation
git rebase的時候捅婁子了,怎麼辦?線上等……
Python crawler actual combat details: crawling home of pictures
数据产品不就是报表吗?大错特错!这分类里有大学问
Did you blog today?
速看!互联网、电商离线大数据分析最佳实践!(附网盘链接)
Every day we say we need to do performance optimization. What are we optimizing?
一篇文章带你了解SVG 渐变知识
IPFS/Filecoin合法性:保护个人隐私不被泄露
I think it is necessary to write a general idempotent component
每个前端工程师都应该懂的前端性能优化总结:
It's so embarrassing, fans broke ten thousand, used for a year!
Didi elasticsearch cluster cross version upgrade and platform reconfiguration
Why do private enterprises do party building? ——Special subject study of geek state holding Party branch
Want to do read-write separation, give you some small experience
6.1.1 handlermapping mapping processor (1) (in-depth analysis of SSM and project practice)
比特币一度突破14000美元,即将面临美国大选考验
华为云“四个可靠”的方法论