Java/PDF RTF/Column
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
An example using MultiColumnText with irregular columns
/*
* $Id: MultiColumnIrregular.java,v 1.7 2005/05/09 11:52:45 blowagie Exp $ $Name: $
*
* This code is part of the "iText Tutorial".
* You can find the complete tutorial at the following address:
* http://itextdocs.lowagie.ru/tutorial/
*
* This code is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE.
*
* itext-questions@lists.sourceforge.net
*/
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.MultiColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
/**
* An example using MultiColumnText with irregular columns.
*/
public class MultiColumnIrregular {
/**
* An example using MultiColumnText with irregular columns.
* @param args no arguments needed
*/
public static void main(String[] args) {
try {
// step 1
Document document = new Document();
OutputStream out = new FileOutputStream("MultiColumnIrregular.pdf");
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
// calculate diamond shaped hole
float diamondHeight = 400;
float diamondWidth = 400;
float gutter = 10;
float bodyHeight = document.top() - document.bottom();
float colMaxWidth = (document.right() - document.left() - (gutter * 2)) / 2f;
float diamondTop = document.top() - ((bodyHeight - diamondHeight) / 2f);
float diamondInset = colMaxWidth - (diamondWidth / 2f);
float centerX = (document.right() - document.left()) / 2 + document.left();
// draw stuff
PdfContentByte cb = writer.getDirectContentUnder();
MultiColumnText mct = new MultiColumnText(document.top() - document.bottom());
// setup column 1
float[] left = {document.left(), document.top(), document.left(), document.bottom()};
float[] right = {document.left() + colMaxWidth, document.top(),
document.left() + colMaxWidth, diamondTop,
document.left() + diamondInset, diamondTop - diamondHeight / 2,
document.left() + colMaxWidth, diamondTop - diamondHeight,
document.left() + colMaxWidth, document.bottom()
};
mct.addColumn(left, right);
// setup column 2
left = new float[] { document.right() - colMaxWidth, document.top(),
document.right() - colMaxWidth, diamondTop,
document.right() - diamondInset, diamondTop - diamondHeight / 2,
document.right() - colMaxWidth, diamondTop - diamondHeight,
document.right() - colMaxWidth, document.bottom()
};
right = new float[] { document.right(), document.top(), document.right(), document.bottom() };
mct.addColumn(left, right);
// add text
for (int i=0; i<8; i++) {
mct.addElement(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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
mct.addElement(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.]\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
mct.addElement(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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
mct.addElement(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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
mct.addElement(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.", FontFactory.getFont(FontFactory.HELVETICA, 12)));
}
do {
cb.setLineWidth(5);
cb.setColorStroke(Color.GRAY);
cb.moveTo(centerX , document.top());
cb.lineTo(centerX, document.bottom());
cb.stroke();
cb.moveTo(centerX, diamondTop);
cb.lineTo(centerX - (diamondWidth/2), diamondTop - (diamondHeight / 2));
cb.lineTo(centerX, diamondTop - diamondHeight);
cb.lineTo(centerX + (diamondWidth/2), diamondTop - (diamondHeight / 2));
cb.lineTo(centerX, diamondTop);
cb.setColorFill(Color.GRAY);
cb.fill();
document.add(mct);
mct.nextColumn();
} while (mct.isOverflow());
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Multi Column Regular Columns
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.MultiColumnText;
import com.lowagie.text.pdf.PdfWriter;
public class MultiColumnRegularColumnsPDF {
public static void main(String[] args) {
try {
Document document = new Document();
OutputStream out = new FileOutputStream("MultiColumnRegularColumnsPDF.pdf");
PdfWriter.getInstance(document, out);
document.open();
MultiColumnText mct = new MultiColumnText();
mct.setColumnsRightToLeft(true);
mct.addRegularColumns(document.left(), document.right(), 10f, 3);
for (int i = 0; i < 30; i++) {
mct.addElement(new Paragraph(String.valueOf(i + 1)));
Paragraph p = new Paragraph("text text text text text text text text text text text ",
FontFactory.getFont("Helvetica", 10, Font.NORMAL, Color.BLACK));
p.setAlignment(Element.ALIGN_LEFT);
p.setLeading(12f);
mct.addElement(p);
}
document.add(mct);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Multi Column Simple Demo
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.MultiColumnText;
import com.lowagie.text.pdf.PdfWriter;
public class MultiColumnSimplePDF {
public static void main(String[] args) {
try {
Document document = new Document();
OutputStream out = new FileOutputStream("MultiColumnSimplePDF.pdf");
PdfWriter.getInstance(document, out);
document.open();
MultiColumnText mct = new MultiColumnText();
mct.addRegularColumns(document.left(), document.right(), 10f, 3);
for (int i = 0; i < 30; i++) {
mct.addElement(new Paragraph(String.valueOf(i + 1)));
Paragraph p = new Paragraph("text text text text text text text text text text text text text text text text text text text text text text text text text text text ", FontFactory.getFont("Helvetica", 10, Font.BOLDITALIC, Color.BLACK));
p.setAlignment(Element.ALIGN_CENTER);
p.setLeading(12f);
mct.addElement(p);
}
document.add(mct);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Three Columns
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
public class ThreeColumnsPDF {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("ThreeColumnsPDF.pdf"));
document.open();
BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 11, Font.NORMAL);
Phrase col1 = new Phrase(15, "col1", font);
Phrase col2 = new Phrase(15, "col2", font);
Phrase col3 = new Phrase(15, "col3", font);
for (int i = 0; i < 40; i++) {
col1.add("col 1\n");
col2.add("col 2\n");
col3.add("col 3\n");
}
PdfContentByte cb = writer.getDirectContent();
ColumnText ct = new ColumnText(cb);
ct.setSimpleColumn(col1, 60, 300, 100, 300 + 28 * 15, 15, Element.ALIGN_CENTER);
ct.go();
ct.setSimpleColumn(col2, 105, 300, 150, 300 + 28 * 15, 15, Element.ALIGN_RIGHT);
ct.go();
ct.setSimpleColumn(col3, 160, 300, 500, 300 + 28 * 15, 15, Element.ALIGN_LEFT);
ct.go();
} catch (Exception e) {
System.err.println(e.getMessage());
}
document.close();
}
}
Writes text in irregular columns that can be added at an absolute position
/*
* $Id: ColumnIrregular.java,v 1.6 2006/09/14 22:52:48 xlv Exp $
* $Name: $
*
* This code is part of the "iText Tutorial".
* You can find the complete tutorial at the following address:
* http://itextdocs.lowagie.ru/tutorial/
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* itext-questions@lists.sourceforge.net
*/
//package com.lowagie.examples.objects.columns;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Image;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* Writes text in irregular columns that can be added at an absolute position.
*/
public class ColumnIrregular {
/**
* Demonstrates the use of ColumnText.
* @param args no arguments needed
*/
public static void main(String[] args) {
System.out.println("Irregular Columns");
// step 1: creation of a document-object
Document document = new Document();
try {
// step 2: creation of the writer
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("columnirregular.pdf"));
// step 3: we open the document
document.open();
// step 4:
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 11, Font.NORMAL);
// we grab the contentbyte and do some stuff with it
PdfContentByte cb = writer.getDirectContent();
PdfTemplate t = cb.createTemplate(600, 800);
Image caesar = Image.getInstance("caesar_coin.jpg");
cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
t.setGrayFill(0.75f);
t.moveTo(310, 112);
t.lineTo(280, 60);
t.lineTo(340, 60);
t.closePath();
t.moveTo(310, 790);
t.lineTo(310, 710);
t.moveTo(310, 580);
t.lineTo(310, 122);
t.stroke();
cb.addTemplate(t, 0, 0);
ColumnText ct = new ColumnText(cb);
ct.addText(new Phrase("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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
ct.addText(new Phrase("[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.]\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
ct.addText(new Phrase("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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
ct.addText(new Phrase("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.\n", FontFactory.getFont(FontFactory.HELVETICA, 12)));
ct.addText(new Phrase("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.", FontFactory.getFont(FontFactory.HELVETICA, 12)));
float[] left1 = {70,790, 70,60};
float[] right1 = {300,790, 300,700, 240,700, 240,590, 300,590, 300,106, 270,60};
float[] left2 = {320,790, 320,700, 380,700, 380,590, 320,590, 320,106, 350,60};
float[] right2 = {550,790, 550,60};
int status = 0;
int column = 0;
while ((status & ColumnText.NO_MORE_TEXT) == 0) {
if (column == 0) {
ct.setColumns(left1, right1);
column = 1;
}
else {
ct.setColumns(left2, right2);
column = 0;
}
status = ct.go();
ct.setYLine(790);
ct.setAlignment(Element.ALIGN_JUSTIFIED);
status = ct.go();
if ((column == 0) && ((status & ColumnText.NO_MORE_COLUMN) != 0)) {
document.newPage();
cb.addTemplate(t, 0, 0);
cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
}
}
}
catch(DocumentException de) {
System.err.println(de.getMessage());
}
catch(IOException ioe) {
System.err.println(ioe.getMessage());
}
// step 5: we close the document
document.close();
}
}