Java 类com.lowagie.text.Document 实例源码

项目:rapidminer    文件:ImageExporter.java   
private void exportVectorGraphics(String formatName, File outputFile) throws ImageExportException {
    Component component = printableComponent.getExportComponent();
    int width = component.getWidth();
    int height = component.getHeight();
    try (FileOutputStream fs = new FileOutputStream(outputFile)) {
        switch (formatName) {
            case PDF:
                // create pdf document with slightly increased width and height
                // (otherwise the image gets cut off)
                Document document = new Document(new Rectangle(width + 5, height + 5));
                PdfWriter writer = PdfWriter.getInstance(document, fs);
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(width, height);
                Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
                component.print(g2);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
                document.close();
                break;
            case SVG:
                exportFreeHep(component, fs, new SVGGraphics2D(fs, new Dimension(width, height)));
                break;
            case EPS:
                exportFreeHep(component, fs, new PSGraphics2D(fs, new Dimension(width, height)));
                break;
            default:
                // cannot happen
                break;
        }
    } catch (Exception e) {
        throw new ImageExportException(I18N.getMessage(I18N.getUserErrorMessagesBundle(),
                "error.image_export.export_failed"), e);
    }
}
项目:citizensLoader4a    文件:PDFTextWritter.java   
/**
     * Título del documento.
     * @param document Documento en cuestión
     * @throws DocumentException Excepcion generada por algún problema
     */
    private void addTitlePage(Document document) throws DocumentException {
        Paragraph preface = new Paragraph();
        addEmptyLine(preface, 1);
        preface.add(new Paragraph("CitizensLoader PDF", catFont));

//      addEmptyLine(preface, 1);
//      // Will create: Report generated by: _name, _date
//      preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
//              smallBold));
//      addEmptyLine(preface, 3);
//      preface.add(new Paragraph("This document describes something which is very important ", smallBold));
//
//      addEmptyLine(preface, 8);
//
//      preface.add(new Paragraph(
//              "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
//              redFont));
//
//      document.add(preface);
//      // Start a new page
//      document.newPage();
        document.add(preface);
        addEmptyLine(preface, 2);
    }
项目:unitimes    文件:PDFPrinter.java   
@Override
public void close() throws IOException {
    try {
        float width = 0;
        float[] w = new float[iMaxWidth.length - iHiddenColumns.size()]; int wi = 0;
        for (int i = 0; i < iMaxWidth.length; i++)
            if (!iHiddenColumns.contains(i)) { width += 15f + iMaxWidth[i]; w[wi++] = iMaxWidth[i]; }
        Document document = new Document(new Rectangle(60f + width, 60f + width * 0.75f), 30f, 30f, 30f, 30f);
        PdfWriter writer = PdfWriter.getInstance(document, iOutput);
        writer.setPageEvent(new PdfEventHandler());
        document.open();
        iTable.setWidths(w);
        document.add(iTable);
        document.close();
    } catch (DocumentException e) {
        throw new IOException(e.getMessage(), e);
    }
}
项目:DWSurvey    文件:DocExportUtil.java   
public void createDoc() throws FileNotFoundException{
     /** 创建Document对象(word文档)  */
       Rectangle rectPageSize = new Rectangle(PageSize.A4);
       rectPageSize = rectPageSize.rotate();
       // 创建word文档,并设置纸张的大小
       doc = new Document(PageSize.A4);
       file=new File(path+docFileName);
       fileOutputStream=new FileOutputStream(file);
       /** 建立一个书写器与document对象关联,通过书写器可以将文档写入到输出流中 */
       RtfWriter2.getInstance(doc, fileOutputStream );
       doc.open();
       //设置页边距,上、下25.4毫米,即为72f,左、右31.8毫米,即为90f  
       doc.setMargins(90f, 90f, 72f, 72f);
       //设置标题字体样式,粗体、二号、华文中宋  
       tfont  = DocStyleUtils.setFontStyle("华文中宋", 22f, Font.BOLD);  
       //设置正文内容的字体样式,常规、三号、仿宋_GB2312  
       bfont = DocStyleUtils.setFontStyle("仿宋_GB2312", 16f, Font.NORMAL);
}
项目:citizensLoader4a    文件:PDFTextWritter.java   
@Override
public void createDocument(String documentName, String content) throws CitizenException {
    String realPath = FILE_PATH + documentName + ".pdf";
    Document doc = new Document();
    try {
        PdfWriter.getInstance(doc, new FileOutputStream(realPath));
        doc.open();
        addMetaData(doc);
        addTitlePage(doc);
        addContent(doc, content);
    } catch (DocumentException | FileNotFoundException e) {
        throw new CitizenException("Error al generar documento pdf" +
                " ["+ FILE_PATH+documentName+".pdf] | ["+this.getClass().getName()+"]");
    } finally {
        if (doc != null) {
            doc.close();
        }
    }

}
项目:twainBDirect    文件:ImageManager.java   
public static void convertWriteToPdf(BufferedImage bufeBufferedImage, String path) {
    try {
        //Image img = Image.getInstance("C:\\Users\\SOFTWARE1\\Desktop\\boshtwain4JImages\\testcapture1507134499431.jpg");
        Image img = Image.getInstance(bufeBufferedImage, null);
        Document document = new Document(img);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
        //--
        document.open();
        img.setAbsolutePosition(0, 0);
        //--
        document.add(img);
        //--
        document.close();
    } catch (DocumentException | IOException e) {
        System.out.println("Intern Log : " + e.getMessage());
    }
}
项目:unitimes    文件:PdfExamGridTable.java   
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();
}
项目:unitimes    文件:PdfInstructionalOfferingTableBuilder.java   
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();
  }
项目:unitimes    文件:PdfLegacyReport.java   
public void open(OutputStream out, int mode) throws DocumentException, IOException {
    iOut = out;
    if (mode==sModeText) {
        iPrint = new PrintWriter(iOut);
    } else {
        iNrLines = (mode==sModeLedger?116:50);
        iDoc = new Document(mode==sModeLedger?PageSize.LEDGER.rotate():PageSize.LETTER.rotate());

        PdfWriter.getInstance(iDoc, iOut);

        iDoc.addTitle(iTitle);
        iDoc.addAuthor("UniTime "+Constants.getVersion()+", www.unitime.org");
        iDoc.addSubject(iSubject);
        iDoc.addCreator("UniTime "+Constants.getVersion()+", www.unitime.org");

        iDoc.open();
    }
    iEmpty = true;
    iPageNo = 0; iLineNo = 0;
}
项目:unitimes    文件:PdfEventHandler.java   
/**
   * Print footer string on each page
   * @param writer
   * @param document
   */
  public void onEndPage(PdfWriter writer, Document document) {

    if(getDateTime() == null) {
        setDateTime(new Date());
    }

PdfContentByte cb = writer.getDirectContent();
cb.beginText();
cb.setFontAndSize(getBaseFont(), getFontSize());
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, getDateFormat().format(getDateTime()), 
        document.left(), 20, 0);
cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, String.valueOf(document.getPageNumber()), 
        document.right(), 20, 0);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, MESSAGES.pdfCopyright(Constants.getVersion()),
        (document.left() + document.right()) / 2, 20, 0);
cb.endText();

      return;
  }
项目:Learning-Spring-5.0    文件:PdfView.java   
@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    List<Book> books = (List<Book>) model.get("book");

    PdfPTable table = new PdfPTable(3);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.getDefaultCell().setBackgroundColor(Color.lightGray);

    table.addCell("Book Name");
    table.addCell("Author Name");
    table.addCell("Price");

    for (Book book : books) {
        table.addCell(book.getBookName());
        table.addCell(book.getAuthor());
        table.addCell("" + book.getPrice());
    }
    document.add(table);

}
项目:itext2    文件:SimplePdfTest.java   
@Test
public void testSimplePdf() throws FileNotFoundException, DocumentException {
    // create document
    Document document = PdfTestBase.createPdf("testSimplePdf.pdf");
    try {
        // new page with a rectangle
        document.open();
        document.newPage();
        Annotation ann = new Annotation("Title", "Text");
        Rectangle rect = new Rectangle(100, 100);
        document.add(ann);
        document.add(rect);
    } finally {
        // close document
        if (document != null)
            document.close();
    }

}
项目:itext2    文件:ExtendedFontTest.java   
/**
 * Extended font example.
 * 
 * 
 */
@Test
public void main() throws Exception {
    Document document = new Document();
    RtfWriter2.getInstance(document, PdfTestBase.getOutputStream("ExtendedFont.rtf"));
    document.open();

    // Create a RtfFont with the desired font name.
    RtfFont msComicSans = new RtfFont("Comic Sans MS");

    // Use the RtfFont like any other Font.
    document.add(new Paragraph("This paragraph uses the" + " Comic Sans MS font.", msComicSans));

    // Font size, font style and font colour can also be specified.
    RtfFont bigBoldGreenArial = new RtfFont("Arial", 36, Font.BOLD, Color.GREEN);

    document.add(new Paragraph("This is a really big bold green Arial text", bigBoldGreenArial));
    document.close();
}
项目:OSCAR-ConCert    文件:PdfRecordPrinter.java   
public void start() throws DocumentException,IOException {
    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, FONTSIZE, Font.NORMAL);
    boldFont = new Font(bf,FONTSIZE,Font.BOLD);

    //Create the document we are going to write to
    document = new Document();
    writer = PdfWriterFactory.newInstance(document, os, FontSettings.HELVETICA_10PT);
    // writer = PdfWriter.getInstance(document,os);
    // writer.setPageEvent(new EndPage());
    writer.setStrictImageSequence(true);

    document.setPageSize(PageSize.LETTER);
    document.open();
}
项目:itext2    文件:OpenTypeFontTest.java   
/**
 * Using oth
 */
@Test
public void main() throws Exception {
    // step 1
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    // step 2
    PdfWriter.getInstance(document,
            PdfTestBase.getOutputStream("opentypefont.pdf"));
    // step 3
    document.open();
    // step 4
    BaseFont bf = BaseFont.createFont(PdfTestBase.RESOURCES_DIR
            + "liz.otf", BaseFont.CP1252, true);
    String text = "Some text with the otf font LIZ.";
    document.add(new Paragraph(text, new Font(bf, 14)));
    // step 5
    document.close();
}
项目:itext2    文件:SpaceWordRatioTest.java   
/**
 * Space Word Ratio.
 */
@Test
public void main() throws Exception {
    // step 1
    Document document = new Document(PageSize.A4, 50, 350, 50, 50);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("spacewordratio.pdf"));
    // step 3
    document.open();
    // step 4
    String text = "Flanders International Filmfestival Ghent - Internationaal Filmfestival van Vlaanderen Gent";
    Paragraph p = new Paragraph(text);
    p.setAlignment(Element.ALIGN_JUSTIFIED);
    document.add(p);
    document.newPage();
    writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
    document.add(p);

    // step 5
    document.close();
}
项目:OSCAR-ConCert    文件:CaseManagementPrintPdf.java   
public void onEndPage( PdfWriter writer, Document document ) {
    //Footer contains page numbers and date printed on all pages
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    String strFooter = promoTxt + " " + formatter.format(now);

    float textBase = document.bottom();
    cb.beginText();
    cb.setFontAndSize(font.getBaseFont(),FONTSIZE);
    Rectangle page = document.getPageSize();
    float width = page.getWidth();

    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width/2.0f), textBase - 20, 0);

    strFooter = "-" + writer.getPageNumber() + "-";
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width/2.0f), textBase-10, 0);

    cb.endText();
    cb.restoreState();
}
项目:document-management-system    文件:PDFUtils.java   
/**
 * Merge several PDFs into a new one
 */
public static void merge(List<InputStream> inputs, OutputStream output) throws IOException, DocumentException {
    Document document = new Document();

    try {
        PdfSmartCopy copy = new PdfSmartCopy(document, output);
        document.open();

        for (InputStream is : inputs) {
            PdfReader reader = new PdfReader(is);

            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                copy.addPage(copy.getImportedPage(reader, i));
            }
        }

        output.flush();
        document.close();
    } finally {
        IOUtils.closeQuietly(output);
    }
}
项目:itext2    文件:FixedFontWidthTest.java   
/**
 * Changing the width of font glyphs.
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {
    // step 1
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    // step 2
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream("fixedfontwidth.pdf"));
    // step 3
    document.open();
    // step 4
    BaseFont bf = BaseFont.createFont("Helvetica", "winansi", false, false, null, null);
    int widths[] = bf.getWidths();
    for (int k = 0; k < widths.length; ++k) {
        if (widths[k] != 0)
            widths[k] = 1000;
    }
    bf.setForceWidthsOutput(true);
    document.add(new Paragraph("A big text to show Helvetica with fixed width.", new Font(bf)));
    // step 5
    document.close();
}
项目:itext2    文件:UnicodePdfTest.java   
@Test
public void testSimplePdf() throws FileNotFoundException, DocumentException {

    BaseFont font = null;
    try {
        font = BaseFont.createFont("LiberationSerif-Regular.ttf", BaseFont.IDENTITY_H, false);
    }
    catch (IOException ioe) {
        // nop
    }
    Document document = null;
    try {
        document = PdfTestBase.createPdf("unicode.pdf");
        // new page with a rectangle
        document.open();            
        Element unicodeParagraph = new Paragraph(INPUT, new Font(font, 12));
        document.add(unicodeParagraph);
    } 
    finally {
        // close document
        if (document != null)
            document.close();
    }
}
项目:OSCAR-ConCert    文件:OscarChartPrinter.java   
public OscarChartPrinter(HttpServletRequest request, OutputStream os) throws DocumentException,IOException {
    this.request = request;
    this.os = os;

    document = new Document();
    // writer = PdfWriterFactory.newInstance(document, os, FontSettings.HELVETICA_10PT);

    writer = PdfWriter.getInstance(document,os);
    writer.setPageEvent(new EndPage());
    document.setPageSize(PageSize.LETTER);
    document.open();
    //Create the font we are going to print to
       bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
       font = new Font(bf, FONTSIZE, Font.NORMAL);
       boldFont = new Font(bf,FONTSIZE,Font.BOLD);
}
项目:itext2    文件:DrawingTextTest.java   
/**
 * 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();

}
项目:OSCAR-ConCert    文件:TicklerPrinter.java   
public void onEndPage(PdfWriter writer, Document document) {
    //Footer contains page numbers and date printed on all pages
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    String strFooter = promoTxt + " " + formatter.format(now);

    float textBase = document.bottom();
    cb.beginText();
    cb.setFontAndSize(font.getBaseFont(), FONTSIZE);
    Rectangle page = document.getPageSize();
    float width = page.getWidth();
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 20, 0);

    strFooter = "-" + writer.getPageNumber() + "-";
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 10, 0);

    cb.endText();
    cb.restoreState();
}
项目:dhis2-core    文件:PdfFormController.java   
@RequestMapping( value = "/programStage/{programStageUid}", method = RequestMethod.GET )
public void getFormPdfProgramStage( @PathVariable String programStageUid, HttpServletRequest request,
    HttpServletResponse response, OutputStream out ) throws Exception
{
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance( document, baos );

    PdfFormFontSettings pdfFormFontSettings = new PdfFormFontSettings();

    PdfDataEntryFormUtil.setDefaultFooterOnDocument( document, request.getServerName(),
        pdfFormFontSettings.getFont( PdfFormFontSettings.FONTTYPE_FOOTER ) );

    pdfDataEntryFormService.generatePDFDataEntryForm( document, writer, programStageUid,
        PdfDataEntryFormUtil.DATATYPE_PROGRAMSTAGE,
        PdfDataEntryFormUtil.getDefaultPageSize( PdfDataEntryFormUtil.DATATYPE_PROGRAMSTAGE ),
        pdfFormFontSettings, i18nManager.getI18nFormat() );

    String fileName = programStageService.getProgramStage( programStageUid ).getName() + " " +
        DateUtils.getMediumDateString() + ".pdf";

    contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PDF, CacheStrategy.NO_CACHE, fileName, true );
    response.setContentLength( baos.size() );

    baos.writeTo( out );
}
项目:itext2    文件:OpenApplicationTest.java   
/**
 * Creates a document with Named Actions.
 * 
 * @param args The file to open
 */
public void main(String... args) throws Exception {

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    // step 2: we create a writer that listens to the document
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream("OpenApplication.pdf"));
    // step 3: we open the document
    document.open();
    // step 4: we add some content
    String application = args[0];
    Paragraph p = new Paragraph(new Chunk("Click to open " + application).setAction(
            new PdfAction(application, null, null, null)));
    document.add(p);

    // step 5: we close the document
    document.close();

}
项目:itext2    文件:PRStream.java   
/**
 * Sets the data associated with the stream, either compressed or
 * uncompressed. Note that the data will never be compressed if
 * Document.compress is set to false.
 * 
 * @param data raw data, decrypted and uncompressed.
 * @param compress true if you want the stream to be compressed.
 * @param compressionLevel  a value between -1 and 9 (ignored if compress == false)
 * @since   iText 2.1.3
 */
public void setData(byte[] data, boolean compress, int compressionLevel) {
    remove(PdfName.FILTER);
    this.offset = -1;
    if (Document.compress && compress) {
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Deflater deflater = new Deflater(compressionLevel);
            DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater);
            zip.write(data);
            zip.close();
            deflater.end();
            bytes = stream.toByteArray();
            this.compressionLevel = compressionLevel;
        }
        catch (IOException ioe) {
            throw new ExceptionConverter(ioe);
        }
        put(PdfName.FILTER, PdfName.FLATEDECODE);
    }
    else
        bytes = data;
    setLength(bytes.length);
}
项目:itext2    文件:HtmlWriter.java   
/**
* Constructs a <CODE>HtmlWriter</CODE>.
*
* @param doc     The <CODE>Document</CODE> that has to be written as HTML
* @param os      The <CODE>OutputStream</CODE> the writer has to write to.
*/

   protected HtmlWriter(Document doc, OutputStream os) {
       super(doc, os);

       document.addDocListener(this);
       this.pageN = document.getPageNumber();
       try {
           os.write(LT);
           os.write(getISOBytes(HtmlTags.HTML));
           os.write(GT);
           os.write(NEWLINE);
           os.write(TAB);
           os.write(LT);
           os.write(getISOBytes(HtmlTags.HEAD));
           os.write(GT);
       }
       catch(IOException ioe) {
           throw new ExceptionConverter(ioe);
       }
   }
项目:itext2    文件:DifferentFontsTest.java   
/**
 * Using FontSelector.
 */
@Test
public void main() throws Exception {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream("differentfonts.pdf"));
    // step 3
    document.open();
    // step 4
    Paragraph p = new Paragraph();
    p.add(new Chunk("This text is in Times Roman. This is ZapfDingbats: ", new Font(Font.TIMES_ROMAN, 12)));
    p.add(new Chunk("abcdefghijklmnopqrstuvwxyz", new Font(Font.ZAPFDINGBATS, 12)));
    p.add(new Chunk(". This is font Symbol: ", new Font(Font.TIMES_ROMAN, 12)));
    p.add(new Chunk("abcdefghijklmnopqrstuvwxyz", new Font(Font.SYMBOL, 12)));
    document.add(new Paragraph(p));
    // step 5
    document.close();

}
项目:itext2    文件:HelloWorldTest.java   
/**
 * Generates a PDF file 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 PDF-stream to a file
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream("HelloWorld.pdf"));

    // 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();
}
项目:OSCAR-ConCert    文件:ConsultationPDFCreator.java   
/**
 * Prints the consultation request.
 * @throws IOException when an error with the output stream occurs
 * @throws DocumentException when an error in document construction occurs
 */
public void printPdf(LoggedInInfo loggedInInfo) throws IOException, DocumentException {

    // Create the document we are going to write to
    document = new Document();
    // PdfWriter.getInstance(document, os);
    PdfWriterFactory.newInstance(document, os, FontSettings.HELVETICA_10PT);

    document.setPageSize(PageSize.LETTER);
    document.addTitle(getResource("msgConsReq"));
    document.addCreator("OSCAR");
    document.open();

    // Create the fonts that we are going to use
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
            BaseFont.NOT_EMBEDDED);
    headerFont = new Font(bf, 14, Font.BOLD);
    infoFont = new Font(bf, 12, Font.NORMAL);
    font = new Font(bf, 9, Font.NORMAL);
    boldFont = new Font(bf, 10, Font.BOLD);
    bigBoldFont = new Font(bf, 12, Font.BOLD);

    createConsultationRequest(loggedInInfo);

    document.close();
}
项目:OSCAR-ConCert    文件:PdfRecordPrinter.java   
public void onEndPage( PdfWriter writer, Document document ) {
    //Footer contains page numbers and date printed on all pages
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    String strFooter = promoTxt + " " + formatter.format(now);

    float textBase = document.bottom();
    cb.beginText();
    cb.setFontAndSize(font.getBaseFont(),FONTSIZE);
    Rectangle page = document.getPageSize();
    float width = page.getWidth();            
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width/2.0f), textBase - 20, 0);

    strFooter = "-" + writer.getPageNumber() + "-";
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width/2.0f), textBase-10, 0);

    cb.endText();
    cb.restoreState();
}
项目:OSCAR-ConCert    文件:PageNumberStamper.java   
public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    String text = "Page " + writer.getPageNumber() + " of ";

    // height where text starts 
    float textBase = document.bottom() - getBaseOffset();
    float textSize = getFont().getWidthPoint(text, getFontSize());
    float width = document.getPageSize().getWidth();
    float center = width / 2.0f;

    cb.beginText();
    cb.setFontAndSize(getFont(), getFontSize());

    cb.setTextMatrix(document.left(), textBase);
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text, center, textBase, 0);
    cb.endText();
    cb.addTemplate(total, center + (textSize / 2.0f), textBase);

    cb.restoreState();
}
项目:itext2    文件:SymbolSubstitutionTest.java   
/**
 * How to substiture special characters with Phrase.getInstance.
 */
@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("SymbolSubstitution.pdf"));

    // step 3: we open the document
    document.open();
    // step 4:
    document.add(Phrase.getInstance("What is the " + (char) 945 + "-coefficient of the " + (char) 946
            + "-factor in the " + (char) 947 + "-equation?\n"));
    for (int i = 913; i < 970; i++) {
        document.add(Phrase.getInstance(" " + i + ": " + (char) i));
    }

    // step 5: we close the document
    document.close();
}
项目:itext2    文件:ImageCellTest.java   
/**
 * A cell with an image.
 * 
 */
@Test
public void main() throws Exception {

    // step 1: creation of a document-object
    Document document = new Document();

    // step 2:
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream("ImageCell.pdf"));

    // step 3: we open the document
    document.open();
    Image image = Image.getInstance(PdfTestBase.RESOURCES_DIR + "otsoe.jpg");
    float[] widths = { 1f, 4f };
    PdfPTable table = new PdfPTable(widths);
    table.addCell("This is my dog");
    table.addCell(image);
    table.addCell("This two");
    table.addCell(new PdfPCell(image, true));
    table.addCell("This three");
    table.addCell(new PdfPCell(image, false));
    document.add(table);

    // step 5: we close the document
    document.close();
}
项目:itext2    文件:MyFirstTableTest.java   
/**
 * 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();
}
项目:sistra    文件:PDFDocument.java   
public void generate(OutputStream os) throws Exception
{
    document = new Document(PageSize.A4, 36, 36, 36, 50);
    writer = PdfWriter.getInstance(document,os);        
    writer.setEncryption(null, null, PdfWriter.AllowCopy | PdfWriter.AllowPrinting, PdfWriter.STRENGTH40BITS);
    writer.setPageEvent(new EndPage(this.getCabecera(),this.getPie(),this.getBarcode(),this.isPaginar()));      
    document.open();                
    //Pintar la cabecera que proceda: No pitar, cabecera normal o cabecera peque�a
    if(!noCabecera) {
        if (tipocabecera.equals(TYPE_HEAD_SMALL)) writeCabecera2();
        else writeCabecera();
    }


    for(int i=0; i<secciones.size(); i++)
    {
        Seccion obj = (Seccion)secciones.get(i);
        obj.write(this);
    }       

    document.close();
}
项目:itext2    文件:HelloWorldTest.java   
/**
 * 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();

}
项目:itext2    文件:PageNumbersWatermarkTest.java   
/**
    * Generates a document with a header containing Page x of y and with a Watermark on every page.
    */
@Test
public void main() throws Exception {
        // step 1: creating the document
           Document doc = new Document(PageSize.A4, 50, 50, 100, 72);
           // step 2: creating the writer
           PdfWriter writer = PdfWriter.getInstance(doc, PdfTestBase.getOutputStream( "pageNumbersWatermark.pdf"));
           // step 3: initialisations + opening the document
           writer.setPageEvent(new PageNumbersWatermarkTest());
           doc.open();
           // step 4: adding content
           String text = "some padding text ";
           for (int k = 0; k < 10; ++k) {
               text += text;
           }
           Paragraph p = new Paragraph(text);
           p.setAlignment(Element.ALIGN_JUSTIFIED);
           doc.add(p);
           // step 5: closing the document
           doc.close();

   }
项目:itext2    文件:PageNumbersWatermarkTest.java   
/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onStartPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onStartPage(PdfWriter writer, Document document) {
    if (writer.getPageNumber() < 3) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.setColorFill(Color.pink);
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        cb.showTextAligned(Element.ALIGN_CENTER, "My Watermark Under " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
}
项目:citizensLoader4a    文件:PDFTextWritter.java   
/**
 * Metadata del documento.
 * @param document Documento en cuestión
 */
private void addMetaData(Document document) {
    document.addTitle("My first PDF");
    document.addSubject("Using iText");
    document.addKeywords("Java, PDF, iText");
    document.addAuthor("Lars Vogel");
    document.addCreator("Lars Vogel");
}