使用ASPOSE在一个word文件的自定义标记处插入另一个word

package mycmf.office;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.aspose.words.Document;
import com.aspose.words.Body;
import com.aspose.words.CompositeNode;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.Node;
import com.aspose.words.NodeCollection;
import com.aspose.words.NodeImporter;
import com.aspose.words.NodeType;
import com.aspose.words.Orientation;
import com.aspose.words.PaperSize;
import com.aspose.words.Paragraph;
import com.aspose.words.Section; 
import com.aspose.words.Range;
 
//aspose-words-18.10-jdk16.jar
public class AsposeWordIns {

    public void main(String[] args) throws IOException {
        
    	//在文档指定符号处插入另一个文件。keyy为自定义符号。
    	DocInsert("{插入文件001}" ,"D:/temp/rep/000.docx","D:/temp/rep/2023.docx","D:/temp/rep/0002.docx", true);
        
    }
    
	
	public void DocInsert(String keyy ,String mainWord,String AddWord,String outWord,boolean isPortrait)    {
		   if (!getLicenseDoc()) { System.out.println("Aspose_word_License Err!");		}	
		   try{
		    Document doc = new Document(mainWord); // 加载要处理的文档
		    //需要进行追加的文档
			Document addDocument = new Document(AddWord);
			DocumentBuilder Builder = new DocumentBuilder(doc); 
			Range range = doc.getRange();
	        NodeCollection runs = doc.getChildNodes(NodeType.PARAGRAPH, true); //获取所有节点
	        int dell = 0 ;
	        for (int i = 0; i < runs.getCount(); i++) {
	            Paragraph r = (Paragraph) runs.get(i);
	            String text = r.getRange().getText();//获取段落文本
	            //System.out.println(i+":"+text);
	            if(text.length()>=keyy.length() && text.indexOf(keyy)>=0) {
	                //指定段落插入表格
	                Builder.moveTo(r);
	                Builder.getPageSetup().setPaperSize(PaperSize.A4);
	                if (isPortrait)
					{
						Builder.getPageSetup().setOrientation(Orientation.PORTRAIT);
					}
					else
					{
						Builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);
					}
	                //range.replace(keyy, "" , true, false); //替换标记为空
	                Node insertAfterNode = Builder.getCurrentParagraph().getPreviousSibling();
	                insertDocumentAfterNode(insertAfterNode, doc , addDocument);
	                r.remove();//删除标记所在行
	                break;
	            } 
	        }	        
	        //doc.updateFields();
	        doc.save(outWord);//新文件地址 
		   }catch (Exception e)
			{
				e.printStackTrace();
			}
	         
	}

	/**
	 * @Description
	 * @param insertAfterNode 插入的位置
	 * @param mainDoc 主文档
	 * @param srcDoc 要拼接进去的文档
	 * @Return void
	 */ 
	private  void insertDocumentAfterNode(Node insertAfterNode, Document mainDoc, Document srcDoc) throws Exception
	{
		if (insertAfterNode.getNodeType() != 8 && insertAfterNode.getNodeType() != 5)
		{
			throw new Exception("The destination node should be either a paragraph or table.");
		}
		else
		{
			CompositeNode dstStory = insertAfterNode.getParentNode();
			Body body = srcDoc.getLastSection().getBody();
			while (null != body.getLastParagraph() && !body.getLastParagraph().hasChildNodes())
			{
				srcDoc.getLastSection().getBody().getLastParagraph().remove();
			}

			NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
			int sectCount = srcDoc.getSections().getCount();

			for (int sectIndex = 0; sectIndex < sectCount; ++sectIndex)
			{
				Section srcSection = srcDoc.getSections().get(sectIndex);
				int nodeCount = srcSection.getBody().getChildNodes().getCount();
				for (int nodeIndex = 0; nodeIndex < nodeCount; ++nodeIndex)
				{
					Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
					Node newNode = importer.importNode(srcNode, true);
					dstStory.insertAfter(newNode, insertAfterNode);
					insertAfterNode = newNode;
				}
			}
		}
	}	
	

    public String basDir(){
        String str = ""; 
        try{
        	str = getClass().getProtectionDomain().getCodeSource().getLocation().getPath().substring(1);
        } catch (Exception e) { }
        if(str.indexOf("WEB-INF")>0){ str =  str.substring(0, (str.indexOf("WEB-INF")-1)  ); }
        if(str.indexOf(":")<5 && str.indexOf(":")>0){
           //win系统	
        }else{
           //unix系统	
           if(str.indexOf("/")>1){  str = "/" + str ; }
        } 
	    return str ;
    }  

	/**
	 * word签名
	 * */
	public boolean getLicenseDoc( ) {
		boolean result = false;
		com.aspose.words.License aposeLic = new com.aspose.words.License();
		String BSD = basDir();
		//System.out.println("LicenseDoc:" + BSD);
		try {
			//InputStream is  = AsposeWord.class.getClassLoader().getResourceAsStream("license.xml");
			// license.xml应放在..\WebRoot\WEB-INF\classes路径下
			File file = new File(BSD+"/WEB-INF/Aspose_license.xml");
			InputStream is  =  new FileInputStream(file);
			aposeLic.setLicense(is);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值