PageRenderTime 36ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/src/CreateWordDoc.java

https://github.com/AndreyLevchenko/html-convertor
Java | 57 lines | 40 code | 9 blank | 8 comment | 2 complexity | c0fb7542f8d38f2e0082ed1dadb73dff MD5 | raw file
  1. import java.io.FileInputStream;
  2. import java.io.FileOutputStream;
  3. import org.apache.poi.hpsf.CustomProperties;
  4. import org.apache.poi.hpsf.DocumentSummaryInformation;
  5. import org.apache.poi.hwpf.HWPFDocument;
  6. import org.apache.poi.hwpf.usermodel.CharacterRun;
  7. import org.apache.poi.hwpf.usermodel.Paragraph;
  8. import org.apache.poi.hwpf.usermodel.ParagraphProperties;
  9. import org.apache.poi.hwpf.usermodel.Range;
  10. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  11. public class CreateWordDoc {
  12. public static void main (String[] args) throws Exception {
  13. // POI apparently can't create a document from scratch,
  14. // so we need an existing empty dummy document
  15. POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:\\work\\tabulaw.andrl\\template.doc"));
  16. HWPFDocument doc = new HWPFDocument(fs);
  17. // centered paragraph with large font size
  18. Range range = doc.getRange();
  19. Paragraph par1 = range.insertAfter(new ParagraphProperties(), 0);
  20. par1.setSpacingAfter(200);
  21. par1.setJustification((byte) 1);
  22. // justification: 0=left, 1=center, 2=right, 3=left and right
  23. CharacterRun run1 = par1.insertAfter("one");
  24. run1.setFontSize(2 * 18);
  25. // font size: twice the point size
  26. // paragraph with bold typeface
  27. Paragraph par2 = run1.insertAfter(new ParagraphProperties(), 0);
  28. par2.setSpacingAfter(200);
  29. CharacterRun run2 = par2.insertAfter("two two two two two two two two two two two two two");
  30. run2.setBold(true);
  31. // paragraph with italic typeface and a line indent in the first line
  32. Paragraph par3 = run2.insertAfter(new ParagraphProperties(), 0);
  33. par3.setFirstLineIndent(200);
  34. par3.setSpacingAfter(200);
  35. CharacterRun run3 = par3.insertAfter("three three three three three three three three three "
  36. + "three three three three three three three three three three three three three three "
  37. + "three three three three three three three three three three three three three three");
  38. run3.setItalic(true);
  39. // add a custom document property (needs POI 3.5; POI 3.2 doesn't save custom properties)
  40. DocumentSummaryInformation dsi = doc.getDocumentSummaryInformation();
  41. CustomProperties cp = dsi.getCustomProperties();
  42. if (cp == null)
  43. cp = new CustomProperties();
  44. cp.put("myProperty", "foo bar baz");
  45. dsi.setCustomProperties(cp);
  46. doc.write(new FileOutputStream("new-hwpf-file.doc"));
  47. }
  48. }