根据xml模板设置标签text并导出xml文件



import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
**/

public class XmlByDom4j {

	/**
	 * 填充Xml模板导出
	 * @author ChenShilin
	 * @date 2017-04-19
	 * @param xmlFilePath XML模板path
	 * @param xmlFileName 导出的xml文件名称
	 * @param mapData 填充的数据
	 */
	public static void FillXmlByMapData(String xmlFilePath,String xmlFileName,Map<String,String> mapData ,HttpServletResponse response){
		try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read(new File(xmlFilePath));
			//得到xml文档根节点元素
			Element root = doc.getRootElement();
			//从根节点开始遍历所有节点
			GetNodes(root,mapData);
			// 创建输出格式(OutputFormat对象)
	        OutputFormat format = OutputFormat.createPrettyPrint();
	        ///设置输出文件的编码,设置成当前服务器的编码
	        format.setEncoding(System.getProperty("file.encoding"));
			XMLWriter writer = new XMLWriter(new FileWriter(new File(xmlFilePath)), format);
			writer.write(doc);
			writer.close();
			OutPutTableByOutputStream(response, xmlFileName, xmlFilePath);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	/**
	 * 从指定节点开始,递归遍历所有子节点 ,
	 * 并且根据节点名称填充相应的数据
	 * @date 2017-04-19
	 * @author chenShiilin
	 * @param node  遍历的节点
	 * @param mapData 需要填充的数据map
	 */
	private static void GetNodes(Element node , Map<String,String> mapData){  
	   //当前节点的名称、文本内容和属性  
	   if(mapData.containsKey(node.getName())){
		   String value = mapData.get(node.getName());
		   if(value != null && value !=""){
			   node.setText(mapData.get(node.getName()));
		   }else{
			   node.setText("");
		   }
	   }
	   //递归遍历当前节点所有的子节点  
	   List<Element> listElement=node.elements();//所有一级子节点的list  
	   for(Element e:listElement){//遍历所有一级子节点  
	       GetNodes(e,mapData);//递归  
	   }  
	}  
	
	/**
	 * 文件下载
	 * Action outputTableByOutputStream
	 * @author ChenShilin
	 * @date 2017-04-19
	 * @param response
	 * @param fileName  文件名称
	 * @param xmlFilePath  XML模板path
	 * @throws Exception
	 */
	private static void OutPutTableByOutputStream(HttpServletResponse response,String fileName,String xmlFilePath) throws Exception
	{
		String contentType = "application/xml";//定义导出文件的格式的字符串
        response.setCharacterEncoding("UTF-8");
        String recommendedName = new String(fileName.getBytes("GB2312"), "ISO8859-1");//设置文件名称的编码格式
        response.setContentType(contentType);//设置导出文件格式 
        response.setHeader("Content-Disposition", "attachment; filename="+recommendedName);
        FileInputStream inputStream = new FileInputStream(new File(xmlFilePath));  
        //3.通过response获取ServletOutputStream对象(out)  
        ServletOutputStream out = response.getOutputStream();  
        byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inputStream.read(buffer))>0){
			out.write(buffer,0,len);
		}
        inputStream.close();  
        out.close();  
        out.flush();
	}
}

转载 https://gitee.com/chensl_846/codes/6kv4f7zx8mgr30ulhic5y36

POI是一个Java库,主要用于处理Microsoft Office文件,包括Excel、Word和PowerPoint等。而Apache PDFBox则是专门用于操作PDF文档的库。如果你想通过Java在PDF模板上添加文字并保存为新的PDF,可以结合这两个库来实现。 首先,你需要在项目中引入这两个库的依赖: ```xml <!-- POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>最新版本号</version> </dependency> <!-- PDFBox --> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>最新版本号</version> </dependency> ``` 然后,你可以使用以下步骤来操作PDF: ```java import org.apache.poi.xwpf.usermodel.*; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; public void addTextToPdf(String templatePath, String outputPath) throws Exception { // 加载PDF模板 PDDocument template = PDDocument.load(new File(templatePath)); // 创建XWPFDocument用于处理Word内容 XWPFDocument wordDoc = new XWPFDocument(); // 添加新段落并写入文本 XWPFParagraph paragraph = wordDoc.createParagraph(); paragraph.setText("这是一段添加到PDF的文字"); // 将Word文档转换为PDPageTree (适用于PDF) List<PDPage> pages = new ArrayList<>(); for (XWPFParagraph p : wordDoc.getParagraphs()) { PDPage pdPage = template.getDocument().getPages().get(0).copy(); PDTextStripper textStripper = new PDFTextStripper(); textStripper.writeText(pdPage, p.getText()); pages.add(pdPage); } // 创建一个新的PDF文档 PDDocument newDoc = new PDDocument(); // 添加页面到新文档 for (PDPage page : pages) { newDoc.addPage(page); } // 将新增内容写入新PDF for (int i = 0; i < pages.size(); i++) { PDPageContentStream contentStream = new PDPageContentStream(newDoc, pages.get(i)); contentStream.drawRenderable(pages.get(i), 1.0f, true); contentStream.close(); } // 保存并关闭新生成的PDF newDoc.save(outputPath); newDoc.close(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值