当前位置:   article > 正文

Java aspose.words转图片,追加内容_new document(inputstream);

new document(inputstream);

 Aspose.words版本19.5

  1. import com.aspose.words.*;
  2. import com.google.common.io.Files;
  3. import lombok.SneakyThrows;
  4. import javax.imageio.ImageIO;
  5. import javax.imageio.stream.ImageInputStream;
  6. import java.awt.*;
  7. import java.awt.Shape;
  8. import java.awt.image.BufferedImage;
  9. import java.io.*;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.UUID;
  13. /**
  14. * @author ninge
  15. * @version
  16. */
  17. public class AsposeUtil {
  18. /**
  19. * licence 验证
  20. *
  21. * @return
  22. * @throws Exception
  23. */
  24. public static boolean getLicense() throws Exception {
  25. boolean result = false;
  26. try {
  27. InputStream is = AsposeUtil.class
  28. .getResourceAsStream("/aspose/license.xml");
  29. License aposeLic = new License();
  30. aposeLic.setLicense(is);
  31. result = true;
  32. is.close();
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. throw e;
  36. }
  37. return result;
  38. }
  39. /**
  40. * 判断是否为空
  41. *
  42. * @param obj 字符串对象
  43. * @return
  44. */
  45. protected static boolean notNull(String obj) {
  46. if (obj != null && !obj.equals("") && !obj.equals("undefined")
  47. && !obj.trim().equals("") && obj.trim().length() > 0) {
  48. return true;
  49. }
  50. return false;
  51. }
  52. /**
  53. * @Description: word和txt文件转换图片
  54. */
  55. public static List<BufferedImage> wordToImg(InputStream inputStream, int pageNum) throws Exception {
  56. OutputStream output=null;
  57. List<BufferedImage> imageList = new ArrayList<BufferedImage>();
  58. try {
  59. Document doc = new Document(inputStream);
  60. ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
  61. options.setPrettyFormat(true);
  62. options.setUseAntiAliasing(true);
  63. options.setUseHighQualityRendering(true);
  64. int pageCount = doc.getPageCount();
  65. if (pageCount > pageNum&&pageNum!=0) {//生成前pageCount张
  66. pageCount = pageNum;
  67. }
  68. for (int i = 0; i < pageCount; i++) {
  69. //doc.save("",options);
  70. output = new ByteArrayOutputStream();
  71. options.setPageIndex(i);
  72. doc.save(output, options);
  73. ImageInputStream imageInputStream= ImageIO.createImageInputStream(parse(output));
  74. imageList.add(ImageIO.read(imageInputStream));
  75. }
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. throw e;
  79. }finally {
  80. output.close();
  81. }
  82. return imageList;
  83. }
  84. public static void singleImg(BufferedImage bufferedImage) throws IOException {
  85. Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics();
  86. g2.setBackground(Color.LIGHT_GRAY);
  87. g2.clearRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
  88. g2.setPaint(Color.RED);
  89. ImageIO.write(bufferedImage,"jpg",new File("/Users/ninge/Desktop/output/"+ UUID.randomUUID()+".jpg"));
  90. }
  91. //outputStream转inputStream
  92. public static ByteArrayInputStream parse(OutputStream out) throws Exception {
  93. ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
  94. ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
  95. baos.close();
  96. swapStream.close();
  97. return swapStream;
  98. }
  99. /**
  100. * word转图片输入流
  101. * @param inputStream
  102. * @param pageNum
  103. * @return
  104. */
  105. @SneakyThrows
  106. public static List<ImageInputStream> getImageInputStreamList(InputStream inputStream,Integer pageNum){
  107. // 验证License
  108. if (!getLicense()) {
  109. return null;
  110. }
  111. OutputStream output=null;
  112. List<ImageInputStream> imageList = new ArrayList<ImageInputStream>();
  113. try {
  114. Document doc = new Document(inputStream);
  115. ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
  116. options.setPrettyFormat(true);
  117. options.setUseAntiAliasing(true);
  118. options.setUseHighQualityRendering(true);
  119. int pageCount = doc.getPageCount();
  120. if (pageCount > pageNum&&pageNum!=0) {//生成前pageCount张
  121. pageCount = pageNum;
  122. }
  123. for (int i = 0; i < pageCount; i++) {
  124. output = new ByteArrayOutputStream();
  125. options.setPageIndex(i);
  126. doc.save(output, options);
  127. ImageInputStream imageInputStream= ImageIO.createImageInputStream(parse(output));
  128. imageList.add(imageInputStream);
  129. imageInputStream.close();
  130. }
  131. output.close();
  132. inputStream.close();
  133. } catch (Exception e) {
  134. e.printStackTrace();
  135. }
  136. return imageList;
  137. }
  138. /**
  139. * doc to pdf
  140. *
  141. * @param docPath doc源文件
  142. * @param pdfPath pdf目标文件
  143. */
  144. public static void doc2PDF(String docPath, String pdfPath) {
  145. try {
  146. // 验证License
  147. if (!getLicense()) {
  148. return;
  149. }
  150. if (notNull(docPath) && notNull(pdfPath)) {
  151. File file = new File(pdfPath);
  152. FileOutputStream os = new FileOutputStream(file);
  153. Document doc = new Document(docPath);
  154. doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
  155. }
  156. } catch (Exception e) {
  157. e.printStackTrace();
  158. }
  159. }
  160. /**
  161. * 合并任数量的图片成一张图片
  162. *
  163. * @param isHorizontal true代表水平合并,fasle代表垂直合并
  164. * @param imgs 待合并的图片数组
  165. * @return
  166. * @throws IOException
  167. */
  168. public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
  169. // 生成新图片
  170. BufferedImage destImage = null;
  171. // 计算新图片的长和高
  172. int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
  173. // 获取总长、总宽、最长、最宽
  174. for (int i = 0; i < imgs.size(); i++) {
  175. BufferedImage img = imgs.get(i);
  176. allw += img.getWidth();
  177. if (imgs.size() != i + 1) {
  178. allh += img.getHeight() + 5;
  179. } else {
  180. allh += img.getHeight();
  181. }
  182. if (img.getWidth() > allwMax) {
  183. allwMax = img.getWidth();
  184. }
  185. if (img.getHeight() > allhMax) {
  186. allhMax = img.getHeight();
  187. }
  188. }
  189. // 创建新图片
  190. if (isHorizontal) {
  191. destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
  192. } else {
  193. destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
  194. }
  195. Graphics2D g2 = (Graphics2D) destImage.getGraphics();
  196. g2.setBackground(Color.LIGHT_GRAY);
  197. g2.clearRect(0, 0, allw, allh);
  198. g2.setPaint(Color.RED);
  199. // 合并所有子图片到新图片
  200. int wx = 0, wy = 0;
  201. for (int i = 0; i < imgs.size(); i++) {
  202. BufferedImage img = imgs.get(i);
  203. int w1 = img.getWidth();
  204. int h1 = img.getHeight();
  205. // 从图片中读取RGB
  206. int[] ImageArrayOne = new int[w1 * h1];
  207. ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
  208. if (isHorizontal) { // 水平方向合并
  209. destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
  210. } else { // 垂直方向合并
  211. destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
  212. }
  213. wx += w1;
  214. wy += h1 + 5;
  215. }
  216. return destImage;
  217. }
  218. /**
  219. * 将BufferedImage转换为InputStream
  220. * @param image
  221. * @return
  222. */
  223. public static InputStream bufferedImageToInputStream(BufferedImage image){
  224. ByteArrayOutputStream os = new ByteArrayOutputStream();
  225. try {
  226. ImageIO.write(image, "png", os);
  227. InputStream input = new ByteArrayInputStream(os.toByteArray());
  228. return input;
  229. } catch (IOException e) {
  230. e.printStackTrace();
  231. }
  232. return null;
  233. }
  234. /**
  235. * 追加红头
  236. * @param title 标题
  237. * @param no 文号
  238. * @param inputStream 阿里云下载文件的流
  239. * @return
  240. * @throws Exception
  241. */
  242. public static InputStream appendRedContent(String title,String no,InputStream inputStream) throws Exception {
  243. // 验证License
  244. if (!getLicense()) {
  245. return null;
  246. }
  247. Document doc = new Document(inputStream);
  248. inputStream.close();
  249. DocumentBuilder builder = new DocumentBuilder(doc);
  250. // Font font = builder.getFont();
  251. // font.setSize(26);//设置字大小
  252. // font.setBold(true);
  253. // font.setColor(Color.RED);
  254. // font.setName("宋体");
  255. //font.setUnderline(Underline.DASH);
  256. //builder.getParagraphFormat().getAlignment()=PageVerticalAlignment.CENTER;
  257. //builder.writeln(title);//追加标题
  258. // font.setSize(16);
  259. // font.setColor(Color.BLACK);
  260. //追加表格 o(╥﹏╥)o
  261. // builder.startTable();
  262. // builder.insertCell();
  263. //
  264. // builder.endRow();
  265. // builder.endTable();
  266. //builder.writeln(no);//追加文号
  267. //builder.insertBreak(BreakType.LINE_BREAK);
  268. //builder.insertImage(AsposeUtil.class.getResourceAsStream("/static/red_line.png"));
  269. // builder.insertHtml("<table style=\"border:0px;width:560px;text-align:center;\" >" +
  270. // "<tr>" +
  271. // "<td style=\"font-size:30px;font-weight:bold;color:red;\">"+title+"</td>" +
  272. // "</tr>" +
  273. // "<tr>" +
  274. // "<td style=\"font-size:20px;font-weight:bold;border-bottom:red solid 3px;line-height:30px\">"+no+"</td>" +
  275. // "</tr>" +
  276. // "</table><br/>",true);
  277. builder.insertHtml("<div style=\"text-align:center;border-bottom:3px solid red;\">" +
  278. "<span style=\"font-size:35px;color:red;display:block;\">"+title+"</span>" +
  279. "<span style=\"font-size:25px;\">"+no+"</span>" +
  280. "</div><br/>");
  281. ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
  282. doc.save(dstStream, SaveFormat.DOCX);
  283. inputStream=new ByteArrayInputStream(dstStream.toByteArray());
  284. dstStream.close();
  285. return inputStream;
  286. }
  287. public static void main(String agrs[]){
  288. //本地word追加开始,只在word文档最开头最佳
  289. File file = new File("/Users/ninge/Desktop/spmk.docx");
  290. InputStream inputStream= appendRedContent("sss","桥通天下〔2020〕12 号",new FileInputStream(file));
  291. byte[] buffer = new byte[inputStream.available()];
  292. inputStream.read(buffer);
  293. File targetFile = new File("/Users/ninge/Desktop/spmk1.docx");
  294. Files.write(buffer, targetFile);
  295. inputStream.close();
  296. //本地word追加结束
  297. //转图片
  298. file = new File("/Users/ninge/Desktop/spmk1.docx");
  299. inputStream = new FileInputStream(file);
  300. List<BufferedImage> wordToImg = wordToImg(inputStream,0);
  301. BufferedImage mergeImage = mergeImage(true, wordToImg);
  302. ImageIO.write(mergeImage, "jpg", new File("/Users/ninge/Desktop/"+
  303. UUID.randomUUID()+".jpg"));
  304. }
  305. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/741009
推荐阅读
相关标签
  

闽ICP备14008679号