下面列出了怎么用com.lowagie.text.Document的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Demonstrates setting text into an RTF drawing object.
*
*
*/
@Test
public void main() throws Exception {
Document document = new Document();
RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("DrawingText.rtf"));
document.open();
// Create a new rectangle RtfShape.
RtfShapePosition position = new RtfShapePosition(1000, 1000, 3000, 2000);
RtfShape shape = new RtfShape(RtfShape.SHAPE_RECTANGLE, position);
// Set the text to display in the drawing object
shape.setShapeText("This text will appear in the drawing object.");
document.add(shape);
document.close();
}
/**
* After the content of the page is written, we put page X of Y at the
* bottom of the page and we add either "Romeo and Juliet" of the title
* of the current act as a header.
*
* @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter,
* com.lowagie.text.Document)
*/
public void onEndPage(PdfWriter writer, Document document) {
int pageN = writer.getPageNumber();
String text = "Page " + pageN + " of ";
float len = bf.getWidthPoint(text, 8);
cb.beginText();
cb.setFontAndSize(bf, 8);
cb.setTextMatrix(280, 30);
cb.showText(text);
cb.endText();
cb.addTemplate(template, 280 + len, 30);
cb.beginText();
cb.setFontAndSize(bf, 8);
cb.setTextMatrix(280, 820);
if (pageN % 2 == 1) {
cb.showText("Romeo and Juliet");
} else {
cb.showText(act);
}
cb.endText();
}
private void createTempFile(String filename, String[] pageContents) throws Exception{
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
for (int i = 0; i < pageContents.length; i++) {
if (i != 0)
document.newPage();
String content = pageContents[i];
Chunk contentChunk = new Chunk(content);
document.add(contentChunk);
}
document.close();
}
@Test
public void testTableSpacingPercentage() throws FileNotFoundException,
DocumentException {
Document document = PdfTestBase
.createPdf("testTableSpacingPercentage.pdf");
document.setMargins(72, 72, 72, 72);
document.open();
PdfPTable table = new PdfPTable(1);
table.setSpacingBefore(20);
table.setWidthPercentage(100);
PdfPCell cell;
cell = new PdfPCell();
Phrase phase = new Phrase("John Doe");
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // This has no
// effect
cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // This has no effect
cell.addElement(phase);
table.addCell(cell);
document.add(table);
document.close();
}
/** Test.
* @throws IOException e
* @throws DocumentException e */
@Test
public void testEmptyPdfCounterRequestContext() throws IOException, DocumentException {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final PdfDocumentFactory pdfDocumentFactory = new PdfDocumentFactory(TEST_APP, null,
output);
final Document document = pdfDocumentFactory.createDocument();
document.open();
final PdfCounterRequestContextReport report = new PdfCounterRequestContextReport(
Collections.<CounterRequestContext> emptyList(),
Collections.<PdfCounterReport> emptyList(),
Collections.<ThreadInformations> emptyList(), true, pdfDocumentFactory, document);
report.toPdf();
report.setTimeOfSnapshot(System.currentTimeMillis());
report.writeContextDetails();
// on ne peut fermer le document car on n'a rien écrit normalement
assertNotNull("PdfCounterRequestContextReport", report);
}
/**
* Generates a PDF file with metadata
*
*/
@Test
public void main() throws Exception {
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(document, PdfTestBase.getOutputStream("HelloWorldMeta.pdf"));
// step 3: we add some metadata open the document
document.addTitle("Hello World example");
document.addSubject("This example explains how to add metadata.");
document.addKeywords("iText, Hello World, step 3, metadata");
document.addCreator("My program using iText");
document.addAuthor("Bruno Lowagie");
document.open();
// step 4: we add a paragraph to the document
document.add(new Paragraph("Hello World"));
// step 5: we close the document
document.close();
}
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
Document pdf = (Document) document;
pdf.setPageSize(PageSize.A3);
pdf.open();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String logo = servletContext.getRealPath("") + File.separator +"resources" + File.separator + "images" + File.separator +"logo" + File.separator + "logo.png";
Image image=Image.getInstance(logo);
image.scaleAbsolute(100f, 50f);
pdf.add(image);
// add a couple of blank lines
pdf.add( Chunk.NEWLINE );
pdf.add( Chunk.NEWLINE );
Font fontbold = FontFactory.getFont("Times-Roman", 16, Font.BOLD);
fontbold.setColor(55, 55, 55);;
pdf.add(new Paragraph("Investment Summary",fontbold));
// add a couple of blank lines
pdf.add( Chunk.NEWLINE );
pdf.add( Chunk.NEWLINE );
}
/**
* Hello World! example
*
*/
@Test
public void main() throws Exception {
// Step 1: Create a new Document
Document document = new Document();
// Step 2: Create a new instance of the RtfWriter2 with the document
// and target output stream.
RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.rtf"));
// Step 3: Open the document.
document.open();
// Step 4: Add content to the document.
document.add(new Paragraph("Hello World!"));
// Step 5: Close the document. It will be written to the target output
// stream.
document.close();
}
public void export(OutputStream out) throws Exception {
int nrCols = getNrColumns();
iDocument = (iForm.getDispMode()==sDispModeInRowHorizontal || iForm.getDispMode()==sDispModeInRowVertical ?
new Document(new Rectangle(Math.max(PageSize.LETTER.getWidth(),60.0f+100.0f*nrCols),Math.max(PageSize.LETTER.getHeight(),60.0f+150f*nrCols)).rotate(), 30, 30, 30, 30)
:
new Document(new Rectangle(Math.max(PageSize.LETTER.getWidth(),60.0f+100.0f*nrCols),Math.max(PageSize.LETTER.getHeight(),60.0f+150f*nrCols)), 30, 30, 30, 30));
PdfEventHandler.initFooter(iDocument, out);
iDocument.open();
printTable();
printLegend();
iDocument.close();
}
/**
* Invokes the createPOQuoteRequestsListPdf method to create a purchase order quote list request pdf document
* and saves it into a file which name and location are specified in the input parameters.
*
* @param po The PurchaseOrderDocument to be used to generate the pdf.
* @param pdfFileLocation The location to save the pdf file.
* @param pdfFilename The name for the pdf file.
* @param institutionName The purchasing institution name.
* @return Collection of errors which are made of the messages from DocumentException.
*/
public Collection savePOQuoteRequestsListPdf(PurchaseOrderDocument po, String pdfFileLocation, String pdfFilename, String institutionName) {
if (LOG.isDebugEnabled()) {
LOG.debug("savePOQuoteRequestsListPDF() started for po number " + po.getPurapDocumentIdentifier());
}
Collection errors = new ArrayList();
try {
Document doc = this.getDocument();
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(pdfFileLocation + pdfFilename));
this.createPOQuoteRequestsListPdf(po, doc, writer, institutionName);
}
catch (DocumentException de) {
LOG.error(de.getMessage(), de);
errors.add(de.getMessage());
}
catch (FileNotFoundException f) {
LOG.error(f.getMessage(), f);
errors.add(f.getMessage());
}
return errors;
}
/**
* Writes a PDF representation of the given list of Grids to the given OutputStream.
*/
public static void toPdf( List<Grid> grids, OutputStream out )
{
if ( hasNonEmptyGrid( grids ) )
{
Document document = openDocument( out );
for ( Grid grid : grids )
{
toPdfInternal( grid, document, 40F );
}
addPdfTimestamp( document, false );
closeDocument( document );
}
}
/**
* We create a writer that listens to the document and directs a PDF-stream to out
*
* @param table
* MBasicTable
* @param document
* Document
* @param out
* OutputStream
* @return DocWriter
* @throws DocumentException
* e
*/
protected DocWriter createWriter(final MBasicTable table, final Document document,
final OutputStream out) throws DocumentException {
final PdfWriter writer = PdfWriter.getInstance(document, out);
// writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft);
// title
if (table.getName() != null) {
final HeaderFooter header = new HeaderFooter(new Phrase(table.getName()), false);
header.setAlignment(Element.ALIGN_LEFT);
header.setBorder(Rectangle.NO_BORDER);
document.setHeader(header);
document.addTitle(table.getName());
}
// simple page numbers : x
// HeaderFooter footer = new HeaderFooter(new Phrase(), true);
// footer.setAlignment(Element.ALIGN_RIGHT);
// footer.setBorder(Rectangle.TOP);
// document.setFooter(footer);
// add the event handler for advanced page numbers : x/y
writer.setPageEvent(new AdvancedPageNumberEvents());
return writer;
}
/**
* Generates an HTML page with the text 'Hello World'
*
*/
@Test
public void main() throws Exception {
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
// and directs a HTML-stream to a file
HtmlWriter.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.html"));
// step 3: we open the document
document.open();
// step 4: we add a paragraph to the document
document.add(new Paragraph("Hello World"));
// step 5: we close the document
document.close();
}
/**
* A very simple Table example.
*
*/
@Test
public void main() throws Exception {
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(document, PdfTestBase.getOutputStream("MyFirstTable.pdf"));
// step 3: we open the document
document.open();
// step 4: we create a table and add it to the document
Table table = new Table(2, 2); // 2 rows, 2 columns
table.addCell("0.0");
table.addCell("0.1");
table.addCell("1.0");
table.addCell("1.1");
document.add(table);
document.add(new Paragraph("converted to PdfPTable:"));
table.setConvert2pdfptable(true);
document.add(table);
// step 5: we close the document
document.close();
}
/**
* Creates a new PDF stream object that will replace a stream in a existing PDF file.
*
* @param reader the reader that holds the existing PDF
* @param conts the new content
* @param compressionLevel the compression level for the content
* @since 2.1.3 (replacing the existing constructor without param compressionLevel)
*/
public PRStream(PdfReader reader, byte[] conts, int compressionLevel) {
this.reader = reader;
offset = -1;
if (Document.compress) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater deflater = new Deflater(compressionLevel);
DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater);
zip.write(conts);
zip.close();
deflater.end();
bytes = stream.toByteArray();
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
put(PdfName.FILTER, PdfName.FLATEDECODE);
} else {
bytes = conts;
}
setLength(bytes.length);
}
public void pdfTableForInstructionalOfferings(
OutputStream out,
ClassAssignmentProxy classAssignment,
ExamAssignmentProxy examAssignment,
InstructionalOfferingListForm form,
String[] subjectAreaIds,
SessionContext context,
boolean displayHeader,
boolean allCoursesAreGiven) throws Exception{
setVisibleColumns(form);
iDocument = new Document(PageSize.A4, 30f, 30f, 30f, 30f);
iWriter = PdfEventHandler.initFooter(iDocument, out);
for (String subjectAreaId: subjectAreaIds) {
pdfTableForInstructionalOfferings(out, classAssignment, examAssignment,
form.getInstructionalOfferings(Long.valueOf(subjectAreaId)),
Long.valueOf(subjectAreaId),
context,
displayHeader, allCoursesAreGiven,
new ClassCourseComparator(form.getSortBy(), classAssignment, false));
}
iDocument.close();
}
/**
* Creates a document with a javascript action.
*
*/
@Test
public void main() throws Exception {
// step 1: creation of a document-object
Document document = new Document();
// step 2:
PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("JavaScriptAction.pdf"));
// step 3: we add Javascript as Metadata and we open the document
document.open();
// step 4: we add some content
Paragraph p = new Paragraph(new Chunk("Click to say Hello").setAction(PdfAction.javaScript(
"app.alert('Hello');\r", writer)));
document.add(p);
// step 5: we close the document
document.close();
}
/**
* General Images example
*/
@Test
public void main() throws Exception {
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Images.pdf"));
// step 3: we open the document
document.open();
// step 4:
document.add(new Paragraph("A picture of my dog: otsoe.jpg"));
Image jpg = Image.getInstance(PdfTestBase.RESOURCES_DIR + "otsoe.jpg");
document.add(jpg);
document.add(new Paragraph("getacro.gif"));
Image gif = Image.getInstance(PdfTestBase.RESOURCES_DIR + "getacro.gif");
document.add(gif);
document.add(new Paragraph("pngnow.png"));
Image png = Image.getInstance(PdfTestBase.RESOURCES_DIR + "pngnow.png");
document.add(png);
document.add(new Paragraph("iText.bmp"));
Image bmp = Image.getInstance(PdfTestBase.RESOURCES_DIR + "iText.bmp");
document.add(bmp);
document.add(new Paragraph("iText.wmf"));
Image wmf = Image.getInstance(PdfTestBase.RESOURCES_DIR + "iText.wmf");
document.add(wmf);
document.add(new Paragraph("iText.tif"));
Image tiff = Image.getInstance(PdfTestBase.RESOURCES_DIR + "iText.tif");
document.add(tiff);
// step 5: we close the document
document.close();
}
/**
* Demonstrates how to measure and scale the width of a Chunk.
*
*/
@Test
public void main() throws Exception {
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Width.pdf"));
// step 3: we open the document
document.open();
// step 4:
Chunk c = new Chunk("quick brown fox jumps over the lazy dog");
float w = c.getWidthPoint();
Paragraph p = new Paragraph("The width of the chunk: '");
p.add(c);
p.add("' is ");
p.add(String.valueOf(w));
p.add(" points or ");
p.add(String.valueOf(w / 72f));
p.add(" inches.");
document.add(p);
document.add(c);
document.add(Chunk.NEWLINE);
c.setHorizontalScaling(0.5f);
document.add(c);
document.add(c);
// step 5: we close the document
document.close();
}
/**
* @see org.kuali.kfs.module.tem.pdf.PdfStream#print(java.io.OutputStream)
* @throws Exception
*/
@Override
public void print(final OutputStream stream) throws Exception {
final Font titleFont = FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD);
final Font headerFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
final Font normalFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
final Document doc = new Document();
final PdfWriter writer = PdfWriter.getInstance(doc, stream);
doc.open();
if(getDocumentNumber()!=null){
Image image=Image.getInstance(new BarcodeHelper().generateBarcodeImage(getDocumentNumber()),null);
doc.add(image);
}
final Paragraph title = new Paragraph("TEM Coversheet", titleFont);
doc.add(title);
final Paragraph faxNumber = new Paragraph("Fax this page to " + SpringContext.getBean(ParameterService.class).getParameterValueAsString(TravelReimbursementDocument.class, FAX_NUMBER), normalFont);
doc.add(faxNumber);
final Paragraph header = new Paragraph("", headerFont);
header.setAlignment(ALIGN_RIGHT);
header.add("Document Number: " + getDocumentNumber());
doc.add(header);
doc.add(getInstructionsParagraph());
doc.add(getMailtoParagraph());
doc.add(Chunk.NEWLINE);
doc.add(getTripInfo());
doc.add(Chunk.NEWLINE);
doc.add(getPersonalInfo());
doc.add(Chunk.NEWLINE);
doc.add(getExpenses());
drawAlignmentMarks(writer.getDirectContent());
doc.close();
writer.close();
}
PdfCopyFieldsImp(OutputStream os, char pdfVersion) throws DocumentException {
super(new PdfDocument(), os);
pdf.addWriter(this);
if (pdfVersion != 0)
super.setPdfVersion(pdfVersion);
nd = new Document();
nd.addDocListener(pdf);
}
PdfHotspotsReport(List<SampledMethod> hotspots, Document document) {
super(document);
assert hotspots != null;
this.hotspots = hotspots;
long total = 0;
for (final SampledMethod hotspot : hotspots) {
total += hotspot.getCount();
}
this.totalCount = total;
}
/**
* General example using cell events.
*
*/
@Test
public void main() throws Exception {
// step1
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
// step2
PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("CellEvents.pdf"));
// step3
document.open();
// step4
CellEventsTest event = new CellEventsTest();
Image im = Image.getInstance(PdfTestBase.RESOURCES_DIR + "otsoe.jpg");
im.setRotationDegrees(30);
PdfPTable table = new PdfPTable(4);
table.addCell("text 1");
PdfPCell cell = new PdfPCell(im, true);
cell.setCellEvent(event);
table.addCell(cell);
table.addCell("text 3");
im.setRotationDegrees(0);
table.addCell(im);
table.setTotalWidth(300);
PdfContentByte cb = writer.getDirectContent();
table.writeSelectedRows(0, -1, 50, 600, cb);
table.setHeaderRows(3);
document.add(table);
// step5
document.close();
}
/**
* Creates a document with outlines.
*
*/
@Test
public void main() throws Exception {
// step 1: creation of a document-object
Document document = new Document(PageSize.A6);
// step 2:
PdfWriter writer = PdfWriter.getInstance(document,
PdfTestBase.getOutputStream("bookmarks.pdf"));
// step 3:
writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
document.open();
// step 4: we grab the ContentByte and do some stuff with it
writer.setPageEvent(new BookmarksTest());
document.add(new Paragraph(
"GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur. Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt. Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt.",
new Font(Font.HELVETICA, 12)));
document.add(new Paragraph(
"[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]",
new Font(Font.HELVETICA, 12)));
document.add(new Paragraph(
"Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix. Is M. Messala, [et P.] M. Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent: perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri. Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur: una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit. His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur. Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.",
new Font(Font.HELVETICA, 12)));
document.add(new Paragraph(
"His rebus adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare. Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant. Ad eas res conficiendas Orgetorix deligitur. Is sibi legationem ad civitates suscipit. In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat. Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset: non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat. Hac oratione adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant.",
new Font(Font.HELVETICA, 12)));
document.add(new Paragraph(
"Ea res est Helvetiis per indicium enuntiata. Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur. Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit. Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit.",
new Font(Font.HELVETICA, 12)));
// step 5: we close the document
document.close();
}
private void setProgramStage_DocumentContent( Document document, PdfWriter writer, String programStageUid )
throws Exception
{
ProgramStage programStage = programStageService.getProgramStage( programStageUid );
if ( programStage == null )
{
throw new RuntimeException( "Error - ProgramStage not found for UID " + programStageUid );
}
else
{
// Get Rectangle with TextBox Width to be used
Rectangle rectangle = new Rectangle( 0, 0, TEXTBOXWIDTH, PdfDataEntryFormUtil.CONTENT_HEIGHT_DEFAULT );
// Create Main Layout table and set the properties
PdfPTable mainTable = getProgramStageMainTable();
// Generate Period List for ProgramStage
List<Period> periods = getProgramStagePeriodList();
// Add Org Unit, Period, Hidden ProgramStageID Field
insertTable_OrgAndPeriod( mainTable, writer, periods );
insertTable_TextRow( writer, mainTable, TEXT_BLANK );
// Add ProgramStage Field - programStage.getId();
insertTable_HiddenValue( mainTable, rectangle, writer,
PdfDataEntryFormUtil.LABELCODE_PROGRAMSTAGEIDTEXTBOX, String.valueOf( programStage.getId() ) );
// Add ProgramStage Content to PDF - [The Main Section]
insertTable_ProgramStage( mainTable, writer, programStage );
// Add the mainTable to document
document.add( mainTable );
}
}
/**
* Generates transaction report
*
* @param errorSortedList list of error'd transactions
* @param reportErrors map containing transactions and the errors associated with each transaction
* @param reportSummary list of summary objects
* @param runDate date report is run
* @param title title of report
* @param fileprefix file prefix of report file
* @param destinationDirectory destination of where report file will reside
*/
public void generateReport(List<Transaction> errorSortedList, Map<Transaction, List<Message>> reportErrors, List<Summary> reportSummary, Date runDate, String title, String fileprefix, String destinationDirectory) {
LOG.debug("generateReport() started");
Font headerFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.BOLD);
Font textFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL);
Document document = new Document(PageSize.A4.rotate());
PageHelper helper = new PageHelper();
helper.runDate = runDate;
helper.headerFont = headerFont;
helper.title = title;
try {
DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
String filename = destinationDirectory + "/" + fileprefix + "_";
filename = filename + dateTimeService.toDateTimeStringForFilename(runDate);
filename = filename + ".pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
writer.setPageEvent(helper);
document.open();
appendReport(document, headerFont, textFont, errorSortedList, reportErrors, reportSummary, runDate);
}
catch (DocumentException de) {
LOG.error("generateReport() Error creating PDF report", de);
throw new RuntimeException("Report Generation Failed: " + de.getMessage());
}
catch (FileNotFoundException fnfe) {
LOG.error("generateReport() Error writing PDF report", fnfe);
throw new RuntimeException("Report Generation Failed: Error writing to file " + fnfe.getMessage());
}
finally {
if ((document != null) && document.isOpen()) {
document.close();
}
}
}
/**
* Generates a PDF file with the 14 standard Type 1 Fonts (using
* FontFactory)
*
*/
@Test
public void main() throws Exception {
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.getInstance(document, PdfTestBase.getOutputStream("FontFactoryType1Fonts.pdf"));
// step 3: we open the document
document.open();
// step 4:
// the 14 standard fonts in PDF
Font[] fonts = new Font[14];
fonts[0] = FontFactory.getFont(FontFactory.COURIER, Font.DEFAULTSIZE, Font.NORMAL);
fonts[1] = FontFactory.getFont(FontFactory.COURIER, Font.DEFAULTSIZE, Font.ITALIC);
fonts[2] = FontFactory.getFont(FontFactory.COURIER, Font.DEFAULTSIZE, Font.BOLD);
fonts[3] = FontFactory.getFont(FontFactory.COURIER, Font.DEFAULTSIZE, Font.BOLD | Font.ITALIC);
fonts[4] = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.NORMAL);
fonts[5] = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.ITALIC);
fonts[6] = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD);
fonts[7] = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLDITALIC);
fonts[8] = FontFactory.getFont(FontFactory.TIMES_ROMAN, Font.DEFAULTSIZE, Font.NORMAL);
fonts[9] = FontFactory.getFont(FontFactory.TIMES_ROMAN, Font.DEFAULTSIZE, Font.ITALIC);
fonts[10] = FontFactory.getFont(FontFactory.TIMES_ROMAN, Font.DEFAULTSIZE, Font.BOLD);
fonts[11] = FontFactory.getFont(FontFactory.TIMES_ROMAN, Font.DEFAULTSIZE, Font.BOLDITALIC);
fonts[12] = FontFactory.getFont(FontFactory.SYMBOL, Font.DEFAULTSIZE, Font.NORMAL);
fonts[13] = FontFactory.getFont(FontFactory.ZAPFDINGBATS, Font.DEFAULTSIZE, Font.NORMAL);
// add the content
for (int i = 0; i < 14; i++) {
document.add(new Paragraph("quick brown fox jumps over the lazy dog", fonts[i]));
}
// step 5: we close the document
document.close();
}
/** {@inheritDoc} */
@Override
public void onEndPage(PdfWriter writer, Document document) {
final int pageN = writer.getPageNumber();
final String text = pageN + " / ";
final float len = bf.getWidthPoint(text, 8);
cb.beginText();
cb.setFontAndSize(bf, 8);
final float width = document.getPageSize().getWidth();
cb.setTextMatrix(width / 2, 30);
cb.showText(text);
cb.endText();
cb.addTemplate(template, width / 2 + len, 30);
}
private void writeTitle(Document document,String title) throws Exception{
Paragraph titleParagraph = new Paragraph(title,titleFont);
titleParagraph.setAlignment(Element.ALIGN_LEFT);
titleParagraph.setLeading(30);
titleParagraph.setSpacingAfter(2);
document.add(titleParagraph);
}
@Test
public void main() throws Exception {
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "shading.pdf"));
document.open();
PdfFunction function1 = PdfFunction.type2(writer, new float[] { 0, 1 },
null, new float[] { .929f, .357f, 1, .298f }, new float[] {
.631f, .278f, 1, .027f }, 1.048f);
PdfFunction function2 = PdfFunction.type2(writer, new float[] { 0, 1 },
null, new float[] { .929f, .357f, 1, .298f }, new float[] {
.941f, .4f, 1, .102f }, 1.374f);
PdfFunction function3 = PdfFunction.type3(writer, new float[] { 0, 1 },
null, new PdfFunction[] { function1, function2 },
new float[] { .708f }, new float[] { 1, 0, 0, 1 });
PdfShading shading = PdfShading.type3(writer,
new CMYKColor(0, 0, 0, 0),
new float[] { 0, 0, .096f, 0, 0, 1 }, null, function3,
new boolean[] { true, true });
PdfContentByte cb = writer.getDirectContent();
cb.moveTo(316.789f, 140.311f);
cb.curveTo(303.222f, 146.388f, 282.966f, 136.518f, 279.122f, 121.983f);
cb.lineTo(277.322f, 120.182f);
cb.curveTo(285.125f, 122.688f, 291.441f, 121.716f, 298.156f, 119.386f);
cb.lineTo(336.448f, 119.386f);
cb.curveTo(331.072f, 128.643f, 323.346f, 137.376f, 316.789f, 140.311f);
cb.clip();
cb.newPath();
cb.saveState();
cb.concatCTM(27.7843f, 0, 0, -27.7843f, 310.2461f, 121.1521f);
cb.paintShading(shading);
cb.restoreState();
cb.sanityCheck();
document.close();
}