List of usage examples for org.apache.poi.hwpf HWPFDocument write
@Override public void write(OutputStream out) throws IOException
From source file:com.google.gdt.handler.impl.WordHandler.java
License:Open Source License
/** * // www . ja v a2 s. c om * @param inputFile * @param pLevel * @throws IOException * @throws InvalidFormatException */ @Override public void handle(String inputFile, ProgressLevel pLevel) throws IOException, InvalidFormatException { String outPutFile = getOuputFileName(inputFile); OutputStream outputStream = new FileOutputStream(outPutFile); InputStream inputStream = new FileInputStream(inputFile); HWPFDocument hDocument = new HWPFDocument(inputStream); Range range = hDocument.getRange(); pLevel.setTrFileName(outPutFile); pLevel.setValue(0); pLevel.setStringPainted(true); pLevel.setMaxValue(range.numParagraphs()); int count = 0; for (int i = 0; i < range.numParagraphs(); i++) { Paragraph paragraph = range.getParagraph(i); int numCharRuns = paragraph.numCharacterRuns(); for (int j = 0; j < numCharRuns; j++) { if (isInterrupted) { outputStream.close(); new File(outPutFile).delete(); pLevel.setString("cancelled"); return; } CharacterRun charRun = paragraph.getCharacterRun(j); String inputText = charRun.text(); if ((null == inputText) || (inputText.trim().equals(""))) continue; String translatedTxt = inputText; //in http post method, all key value pairs are seperated with & if (preferenceModel.getTranslatorType() == TranslatorType.HTTP) inputText = inputText.replaceAll("&", "and"); try { translatedTxt = translator.translate(translatedTxt); charRun.replaceText(inputText, translatedTxt); } catch (Exception e) { logger.log(Level.SEVERE, "Input File : " + inputFile + " cannot translate the text : " + inputText, e); } } count++; pLevel.setValue(count); } pLevel.setString("done"); hDocument.write(outputStream); outputStream.close(); }
From source file:com.icebreak.p2p.front.controller.trade.download.WordParse.java
@Transactional(rollbackFor = Exception.class, value = "transactionManager") public void readwriteWord(HttpServletResponse response, HttpSession session, String _file, Map<String, String> map, List<Map<String, Text>> lst, LoanDemandDO loan, String downType) { //?word?// w w w .j a va 2 s . c o m FileInputStream in; HWPFDocument hdt = null; String filePath = _file; ServletContext application = session.getServletContext(); String serverRealPath = application.getRealPath("/"); String fileTemp = AppConstantsUtil.getYrdUploadFolder() + File.separator + "doc"; File fileDir = new File(fileTemp); if (!fileDir.exists()) { fileDir.mkdir(); } try { in = new FileInputStream(new File(serverRealPath + filePath)); hdt = new HWPFDocument(in); } catch (Exception e1) { logger.error("??", e1); } //??word? Range range = hdt.getRange(); TableIterator it = new TableIterator(range); Table tb = null; while (it.hasNext()) { tb = it.next(); break; } if (lst.size() > 0) { for (int i = 1; i <= lst.size(); i++) { Map<String, Text> replaces = lst.get(i - 1); TableRow tr = tb.getRow(i); // 0 for (int j = 0; j < tr.numCells(); j++) { TableCell td = tr.getCell(j);// ?? // ?? for (int k = 0; k < td.numParagraphs(); k++) { Paragraph para = td.getParagraph(k); String s = para.text(); final String old = s; for (String key : replaces.keySet()) { if (s.contains(key)) { s = s.replace(key, replaces.get(key).getText()); } } if (!old.equals(s)) {// ? para.replaceText(old, s); s = para.text(); } } // end for } } for (int n = lst.size() + 1; n < tb.numRows(); n++) { TableRow tr = tb.getRow(n); tr.delete(); } } for (Map.Entry<String, String> entry : map.entrySet()) { range.replaceText(entry.getKey(), entry.getValue()); } //String fileName = f[f.length-1]; String fileName = System.currentTimeMillis() + _file.substring(_file.lastIndexOf("."), _file.length()); ByteArrayOutputStream ostream = new ByteArrayOutputStream(); try { FileOutputStream out = new FileOutputStream(fileTemp + fileName);//?word hdt.write(ostream); out.write(ostream.toByteArray()); out.flush(); out.close(); } catch (Exception e) { logger.error("?word", e); } Doc2Pdf doc2pdf = new Doc2Pdf(); String pdfAddress = doc2pdf.createPDF(fileTemp + fileName);//wordpdf try { String fileType = ""; if (lst.size() > 0) {//?? fileType = "contract"; } else {//? fileType = "letter"; } DownloadAndPrivewFileTread downThread = new DownloadAndPrivewFileTread(); //this.downloadAndPreviewFile(response, loan.getLoanName(), pdfAddress, downType, fileType);// downThread.setDownType(downType); downThread.setFilePath(pdfAddress); downThread.setResponse(response); downThread.setFileType(fileType); downThread.setProName(loan.getLoanName()); downThread.run(); File pdfFile = new File(pdfAddress); pdfFile.delete(); } catch (Exception e) { logger.error("pdf", e); } }
From source file:File.DOC.WriteDoc.java
/** * @param args the command line arguments *//*from w w w.j a v a 2s. c o m*/ public void Write(String path, String namafile, String content) { File file = new File("D:\\xyz.doc"); try { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file)); HWPFDocument doc = new HWPFDocument(fs); Range range = doc.getRange(); CharacterRun run = range.insertBefore(content.replace("\n", "\013")); run.setBold(true); OutputStream outa = new FileOutputStream(new File(path + namafile + ".doc")); doc.write(outa); out.close(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:javaapplication1.HWPFTest.java
private static void saveWord(String filePath, HWPFDocument doc) throws FileNotFoundException, IOException { FileOutputStream out = null;/*from www . j av a 2s.c o m*/ try { out = new FileOutputStream(filePath); doc.write(out); } finally { out.close(); } }
From source file:Modelo.EscribirWord.java
private void saveWord(String filePath, HWPFDocument doc) throws FileNotFoundException, IOException { FileOutputStream out = null;//from w ww. j ava2 s.com try { out = new FileOutputStream(filePath); doc.write(out); } finally { out.close(); } }
From source file:org.esmerilprogramming.pdfcake.DocumentReplace.java
License:Open Source License
/** * Write the document into a ByteArrayInputStream * @param document/*from www. java2s. c o m*/ * @return * @throws IOException */ private static ByteArrayInputStream getDocumentAsByteArrayIS(HWPFDocument document) throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) { document.write(baos); try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) { return bais; } } }
From source file:poi.hslf.examples.DataExtraction.java
License:Apache License
public static void main(String args[]) throws Exception { if (args.length == 0) { usage();//from ww w. jav a 2 s . co m return; } FileInputStream is = new FileInputStream(args[0]); SlideShow ppt = new SlideShow(is); is.close(); //extract all sound files embedded in this presentation SoundData[] sound = ppt.getSoundData(); for (int i = 0; i < sound.length; i++) { String type = sound[i].getSoundType(); //*.wav String name = sound[i].getSoundName(); //typically file name byte[] data = sound[i].getData(); //raw bytes //save the sound on disk FileOutputStream out = new FileOutputStream(name + type); out.write(data); out.close(); } //extract embedded OLE documents Slide[] slide = ppt.getSlides(); for (int i = 0; i < slide.length; i++) { Shape[] shape = slide[i].getShapes(); for (int j = 0; j < shape.length; j++) { if (shape[j] instanceof OLEShape) { OLEShape ole = (OLEShape) shape[j]; ObjectData data = ole.getObjectData(); String name = ole.getInstanceName(); if ("Worksheet".equals(name)) { //read xls HSSFWorkbook wb = new HSSFWorkbook(data.getData()); } else if ("Document".equals(name)) { HWPFDocument doc = new HWPFDocument(data.getData()); //read the word document Range r = doc.getRange(); for (int k = 0; k < r.numParagraphs(); k++) { Paragraph p = r.getParagraph(k); System.out.println(p.text()); } //save on disk FileOutputStream out = new FileOutputStream(name + "-(" + (j) + ").doc"); doc.write(out); out.close(); } else { FileOutputStream out = new FileOutputStream(ole.getProgID() + "-" + (j + 1) + ".dat"); InputStream dis = data.getData(); byte[] chunk = new byte[2048]; int count; while ((count = dis.read(chunk)) >= 0) { out.write(chunk, 0, count); } is.close(); out.close(); } } } } //Pictures for (int i = 0; i < slide.length; i++) { Shape[] shape = slide[i].getShapes(); for (int j = 0; j < shape.length; j++) { if (shape[j] instanceof Picture) { Picture p = (Picture) shape[j]; PictureData data = p.getPictureData(); String name = p.getPictureName(); int type = data.getType(); String ext; switch (type) { case Picture.JPEG: ext = ".jpg"; break; case Picture.PNG: ext = ".png"; break; case Picture.WMF: ext = ".wmf"; break; case Picture.EMF: ext = ".emf"; break; case Picture.PICT: ext = ".pict"; break; case Picture.DIB: ext = ".dib"; break; default: continue; } FileOutputStream out = new FileOutputStream("pict-" + j + ext); out.write(data.getData()); out.close(); } } } }
From source file:rzd.vivc.astzpte.beans.pagebean.ReportBean.java
public String generateReport(User usr) { HWPFDocument doc; Ticket ticket = usr.getTickets().get(0); List<UserAnswer> answers = usr.getTickets().get(0).getAnswers(); ArrayList<UserAnswerModel> questions = new ArrayList<>(); for (int i = 0; i < answers.size(); i++) { if (answers.get(i).getAnswer() != null) { questions.add(new UserAnswerModel(answers.get(i), i)); }//from ww w .j av a2 s. c o m } SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat format1 = new SimpleDateFormat("hh:mm"); try (FileInputStream fis = new FileInputStream("c:\\rep\\templ.doc")) { doc = new HWPFDocument(fis); doc.getRange().getParagraph(3).replaceText("(dtBeg)", format.format(ticket.getDt_create())); doc.getRange().getParagraph(9).replaceText("(timeBeg)", format1.format(ticket.getDt_create())); doc.getRange().getParagraph(11).replaceText("(timeFin)", format1.format(ticket.getFinish())); long num = usr.getNum(); /* for (int i = 1; i <= 13; i++) { long mod = num % 10;*/ doc.getRange().replaceText("(num)"/* + (13 - i + 1) + ")"*/, num + ""); /* num = num / 10; }*/ doc.getRange().getParagraph(24).replaceText("(allow1)", usr.getAllowNum() + " " + format.format(usr.getAllowDat())); doc.getRange().replaceText("(tickNum)", ticket.getAnswers().get(0).getQuestion().getTicketTemplate().getNum() + ""); doc.getRange().replaceText("(themeNum)", ticket.getAnswers().get(0).getQuestion().getTicketTemplate().getTheme().getId() + ""); doc.getRange().replaceText("(themeName)", ticket.getAnswers().get(0).getQuestion().getTicketTemplate().getTheme().getName()); int count = 0; for (int i = 1; i <= 50; i++) { UserAnswerModel answerModel = questions.get(i - 1); if (i < 10) { doc.getRange().replaceText("T0" + i, answerModel.getQuestion().getText()); doc.getRange().replaceText("C0" + i, answerModel.givenNumber() + ""); boolean cor = answerModel.correctNumber() == answerModel.givenNumber(); if (cor) { count++; } doc.getRange().replaceText("Y0" + i, cor ? " " : " "); doc.getRange().replaceText("B0" + i, cor ? 1 + "" : 0 + ""); } else { doc.getRange().replaceText("T" + i, answerModel.getQuestion().getText()); doc.getRange().replaceText("C" + i, answerModel.givenNumber() + ""); boolean cor = answerModel.correctNumber() == answerModel.givenNumber(); if (cor) { count++; } doc.getRange().replaceText("Y" + i, cor ? " " : " "); doc.getRange().replaceText("B" + i, cor ? 1 + "" : 0 + ""); } } doc.getRange().replaceText("BT", count + ""); doc.getRange().replaceText("BT", count + ""); FileOutputStream fos = new FileOutputStream("c:\\rep\\" + ticket.getId() + ".doc"); doc.write(fos); fos.close(); } catch (FileNotFoundException ex) { Logger.getLogger(ReportBean.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ReportBean.class.getName()).log(Level.SEVERE, null, ex); } return ticket.getId() + ".doc"; }