1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
private Document doc = new Document();
private boolean isUse = false;
private PdfWriter pWriter;
private PdfContentByte pdfCb;
private ColumnText ct;
private float position;
private int statut;
/** generate the PDF to the given OutputSteam */
public void generatePdf(Section rootSection, OutputStream outputStream) throws DocumentException, IOException {
// Bind the document and the outputSteam together.
this.pWriter = PdfWriter.getInstance(this.doc, outputStream);
if (!this.isUse){
this.doc.open();
//Create the column to avoid orphan
this.pdfCb = pWriter.getDirectContent();
this.ct = new ColumnText(this.pdfCb);
this.ct.setSimpleColumn(36, 36, PageSize.A4.getWidth() - 36, PageSize.A4.getHeight() - 36, 18, Element.ALIGN_LEFT);
this.statut = ColumnText.START_COLUMN;
recursiveWalk(rootSection);
this.doc.close();
this.isUse = true;
} else{
throw new IllegalStateException("Instances of this class are like condoms : not thread safe and not reusable. It should be thrown away after use. ;-)");
}
}
/** Accumulates paragraphs for the sections (and its subsections) in this.doc
* @throws IOException */
private void recursiveWalk(Section currentSection) throws DocumentException, IOException{
// Create Title
Chunk pTitle = createTitleChunk(currentSection);
addTitle(pTitle); //Add Title
addBody(currentSection); //Add Body
// Childs (recursive call)
for (Section sSection : currentSection.getSubSections()) {
recursiveWalk(sSection);
}
}
private void addBody(Section currentSection) throws IOException,
DocumentException {
CourseTextFormatter sectionFormatter = new CourseTextFormatter("", currentSection.getBody());
StyleSheet styleBody = new StyleSheet();
styleBody.loadStyle("p", "size", "8"); //Style of the body
List<Element> bodyElements; //Create List with the paragraph
bodyElements = HTMLWorker.parseToList(new StringReader(sectionFormatter.format()), styleBody); //Format text and apply style
for (Element element : bodyElements){
this.ct.addElement(element); //Add element
this.position = this.ct.getYLine(); //Adjust Y pointer
this.statut = this.ct.go(true);
if (!ColumnText.hasMoreText(this.statut)) {
this.ct.addElement(element);
this.ct.setYLine(this.position);
this.ct.go(false);
}
else {
this.doc.newPage();
this.ct.setYLine(PageSize.A4.getHeight() - 36);
this.ct.go();
}
this.doc.add(Chunk.NEWLINE); //Add return to line
}
}
private void addTitle(Chunk pTitle) throws DocumentException {
this.position = this.ct.getYLine(); //Adjust Y pointer
this.ct.setYLine(this.position);
this.ct.addText(pTitle);
this.ct.go();
this.doc.add(Chunk.NEWLINE);
this.doc.add(Chunk.NEWLINE);
} |
Partager