Java Code Examples for com.lowagie.text.Document#setMargins()

The following examples show how to use com.lowagie.text.Document#setMargins() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DocExportUtil.java    From DWSurvey with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: TablePdfTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example 3
Source File: PdfDocumentWriter.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void processLogicalPage( final LogicalPageKey key, final LogicalPageBox logicalPage ) throws DocumentException {

    final float width = (float) StrictGeomUtility.toExternalValue( logicalPage.getPageWidth() );
    final float height = (float) StrictGeomUtility.toExternalValue( logicalPage.getPageHeight() );

    final Rectangle pageSize = new Rectangle( width, height );

    final Document document = getDocument();
    document.setPageSize( pageSize );
    document.setMargins( 0, 0, 0, 0 );

    if ( awaitOpenDocument ) {
      document.open();
      awaitOpenDocument = false;
    }

    final Graphics2D graphics = new PdfGraphics2D( writer.getDirectContent(), width, height, metaData );
    // and now process the box ..
    final PdfLogicalPageDrawable logicalPageDrawable = createLogicalPageDrawable( logicalPage, null );
    logicalPageDrawable.draw( graphics, new Rectangle2D.Double( 0, 0, width, height ) );

    graphics.dispose();

    document.newPage();
  }
 
Example 4
Source File: Prd5321IT.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected TestPdfLogicalPageDrawable createDrawableForTest( final MasterReport report,
    final LogicalPageBox logicalPageBox ) throws DocumentException {
  Document document = new Document();
  PdfWriter writer = PdfWriter.getInstance( document, new NullOutputStream() );
  writer.setLinearPageMode();
  writer.open();

  document.setPageSize( new com.lowagie.text.Rectangle( 700, 500 ) );
  document.setMargins( 10, 10, 10, 10 );
  document.open();

  PdfOutputProcessorMetaData metaData =
      new PdfOutputProcessorMetaData( new ITextFontStorage( BaseFontModule.getFontRegistry() ) );
  metaData.initialize( report.getConfiguration() );
  final Graphics2D graphics = new PdfGraphics2D( writer.getDirectContent(), 700, 500, metaData );

  TestPdfLogicalPageDrawable pdf =
      new TestPdfLogicalPageDrawable( writer, new LFUMap<ResourceKey, Image>( 10 ), '5', graphics );
  pdf.init( logicalPageBox, metaData, report.getResourceManager(), logicalPageBox.getPageGrid().getPage( 0, 0 ) );
  return pdf;
}
 
Example 5
Source File: Prd3820IT.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected TestPdfLogicalPageDrawable createDrawableForTest( final MasterReport report,
    final LogicalPageBox logicalPageBox ) throws DocumentException {
  Document document = new Document();
  PdfWriter writer = PdfWriter.getInstance( document, new NullOutputStream() );
  writer.setLinearPageMode();
  writer.open();

  document.setPageSize( new com.lowagie.text.Rectangle( 700, 500 ) );
  document.setMargins( 10, 10, 10, 10 );
  document.open();

  PdfOutputProcessorMetaData metaData =
      new PdfOutputProcessorMetaData( new ITextFontStorage( BaseFontModule.getFontRegistry() ) );
  metaData.initialize( report.getConfiguration() );
  final Graphics2D graphics = new PdfGraphics2D( writer.getDirectContent(), 700, 500, metaData );

  TestPdfLogicalPageDrawable pdf =
      new TestPdfLogicalPageDrawable( writer, new LFUMap<ResourceKey, Image>( 10 ), '5', graphics );
  pdf.init( logicalPageBox, metaData, report.getResourceManager(), logicalPageBox.getPageGrid().getPage( 0, 0 ) );
  return pdf;
}
 
Example 6
Source File: MarginsTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a PDF document with different pages that have different margins.
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document(PageSize.A5, 36, 72, 108, 180);

	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file

	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Margins.pdf"));

	// step 3: we open the document
	document.open();

	// step 4:
	document.add(new Paragraph(
			"The left margin of this document is 36pt (0.5 inch); the right margin 72pt (1 inch); the top margin 108pt (1.5 inch); the bottom margin 180pt (2.5 inch). "));
	Paragraph paragraph = new Paragraph();
	paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
	for (int i = 0; i < 20; i++) {
		paragraph.add("Hello World, Hello Sun, Hello Moon, Hello Stars, Hello Sea, Hello Land, Hello People. ");
	}
	document.add(paragraph);
	document.setMargins(180, 108, 72, 36);
	document.add(new Paragraph("Now we change the margins. You will see the effect on the next page."));
	document.add(paragraph);
	document.setMarginMirroring(true);
	document.add(new Paragraph("Starting on the next page, the margins will be mirrored."));
	document.add(paragraph);

	// step 5: we close the document
	document.close();
}
 
Example 7
Source File: PurchaseOrderQuoteRequestsPdf.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates an instance of a new Document and set its margins.
 * 
 * @return    The created Document object.
 */
private Document getDocument() throws DocumentException {
    LOG.debug("getDocument() started");
    Document document = new Document(PageSize.A4);
    // Margins: 36pt = 0.5 inch, 72pt = 1 inch. Left, right, top, bottom.
    document.setMargins(9, 9, 25, 36);
    return document;
}
 
Example 8
Source File: PdfDocumentWriter.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void processPhysicalPage( final PageGrid pageGrid, final LogicalPageBox logicalPage, final int row,
    final int col, final PhysicalPageKey pageKey ) throws DocumentException {
  final PhysicalPageBox page = pageGrid.getPage( row, col );
  if ( page == null ) {
    return;
  }

  final float width = (float) StrictGeomUtility.toExternalValue( page.getWidth() );
  final float height = (float) StrictGeomUtility.toExternalValue( page.getHeight() );

  final Rectangle pageSize = new Rectangle( width, height );

  final float marginLeft = (float) StrictGeomUtility.toExternalValue( page.getImageableX() );
  final float marginRight =
      (float) StrictGeomUtility.toExternalValue( page.getWidth() - page.getImageableWidth() - page.getImageableX() );
  final float marginTop = (float) StrictGeomUtility.toExternalValue( page.getImageableY() );
  final float marginBottom =
      (float) StrictGeomUtility.toExternalValue( page.getHeight() - page.getImageableHeight() - page.getImageableY() );

  final Document document = getDocument();
  document.setPageSize( pageSize );
  document.setMargins( marginLeft, marginRight, marginTop, marginBottom );

  if ( awaitOpenDocument ) {
    document.open();
    awaitOpenDocument = false;
  }

  final PdfContentByte directContent = writer.getDirectContent();
  final Graphics2D graphics = new PdfGraphics2D( directContent, width, height, metaData );
  final PdfLogicalPageDrawable logicalPageDrawable = createLogicalPageDrawable( logicalPage, page );
  final PhysicalPageDrawable drawable = createPhysicalPageDrawable( logicalPageDrawable, page );
  drawable.draw( graphics, new Rectangle2D.Double( 0, 0, width, height ) );

  graphics.dispose();

  document.newPage();
}
 
Example 9
Source File: TestDoc.java    From DWSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void exportDoc(String fileName){  
    try {  
        Document doc = new Document();  
        RtfWriter2.getInstance(doc, new FileOutputStream(fileName));  
        // 打开文档  
        doc.open();  
        //设置页边距,上、下25.4毫米,即为72f,左、右31.8毫米,即为90f  
        doc.setMargins(90f, 90f, 72f, 72f);  

        //设置标题字体样式,粗体、二号、华文中宋  
        Font tfont = DocStyleUtils.setFontStyle("华文中宋", 22f, Font.BOLD);  
        //设置正文内容的字体样式,常规、三号、仿宋_GB2312  
        Font bfont = DocStyleUtils.setFontStyle("仿宋_GB2312", 16f, Font.NORMAL);  

        //构建标题,居中对齐,12f表示单倍行距  
        Paragraph title = DocStyleUtils.setParagraphStyle("测试Itext导出Word文档", tfont, 12f, Paragraph.ALIGN_CENTER);  
        //构建正文内容  
        StringBuffer contentSb = new StringBuffer();  
        contentSb.append("最近项目很忙,这个是项目中使用到的,所以现在总结一下,以便今后可以参考使用,");  
        contentSb.append("2011年4月27日 — 2011年5月20日,对以下技术进行使用,");  
        contentSb.append("Itext、");  
        contentSb.append("Excel、");  
        contentSb.append("Word、");  
        contentSb.append("PPT。");  

        //首行缩进2字符,行间距1.5倍行距  
        Paragraph bodyPar = DocStyleUtils.setParagraphStyle(contentSb.toString(), bfont, 32f, 18f);  
        Paragraph bodyEndPar = DocStyleUtils.setParagraphStyle("截至2011年4月28日,各种技术已经完全实现。", bfont, 32f, 18f);  
        //设置空行  
        Paragraph blankRow = new Paragraph(18f, " ", bfont);  
        Paragraph deptPar = DocStyleUtils.setParagraphStyle("(技术开发部盖章)", bfont, 12f, Paragraph.ALIGN_RIGHT);  
        Paragraph datePar = DocStyleUtils.setParagraphStyle("2011-04-30", bfont, 12f, Paragraph.ALIGN_RIGHT);  

        //向文档中添加内容  
        doc.add(title);  
        doc.add(blankRow);  
        doc.add(bodyPar);  
        doc.add(bodyEndPar);  
        doc.add(blankRow);  
        doc.add(blankRow);  
        doc.add(blankRow);  
        doc.add(deptPar);  
        doc.add(datePar);  

        //最后一定要记住关闭  
        doc.close();  

    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}
 
Example 10
Source File: EpubToPdfConverter.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
public File convert(String epubPath) throws IOException,DocumentException {
	applyProperties(epub2pdfProps);
       File epubFile = new File(epubPath);
       if (!(epubFile.canRead())) {
           throw new IOException("Could not read " + epubPath);
       } else {
       	logger.debug("Converting " + epubFile.getAbsolutePath());
       }
       String epubFilename = epubFile.getName();
       String epubFilenameBase = epubFilename.substring(0, epubFilename.length()-5);
       String pdfFilename = epubFilenameBase + ".pdf";

       File outputFile = new File(outputDir.getAbsolutePath() + File.separator + pdfFilename);

       epubIn = Epub.fromFile(epubPath);
       XhtmlHandler.setSourceEpub(epubIn);

       Opf opf = epubIn.getOpf();
       List<String> contentPaths = opf.spineHrefs();
       List<File> contentFiles = new ArrayList<File>();
       for (String path : contentPaths) {
           contentFiles.add(new File(epubIn.getContentRoot(),path));
       }
       Ncx ncx = epubIn.getNcx();
       
       List<NavPoint> ncxToc = new ArrayList<NavPoint>();
       if(ncx != null) {
       	ncxToc.addAll(ncx.getNavPointsFlat());
       }
       
       Tree<TocTreeNode> tocTree = TocTreeNode.buildTocTree(ncx);
       XhtmlHandler.setTocTree(tocTree);
       
       Document doc = new Document();
       boolean pageSizeOK = doc.setPageSize(pageSize);
       boolean marginsOK = doc.setMargins(marginLeftPt, marginRightPt, marginTopPt, marginBottomPt);

       logger.debug("Writing PDF to " + outputFile.getAbsolutePath());
       PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outputFile));
       writer.setStrictImageSequence(true);
       PdfOutline bookmarkRoot = null;

       if (!(pageSizeOK && marginsOK)) {
           throw new RuntimeException("Failed to set PDF page size a/o margins");
       }
       
       int fileCount = contentFiles.size();
       logger.debug("Processing " + fileCount + " HTML file(s): ");
       int currentFile = 0;

       for (File file : contentFiles) {
       	currentFile++;
       	
       	String progressChar;
       	
       	int mod10 = currentFile % 10;
       	if(mod10 == 5)
       		progressChar = "5";
       	else if(mod10 == 0) 
       		progressChar = "0";
       	else
       		progressChar = ".";
       	
       	logger.debug(progressChar);
           if (!(doc.isOpen())) {
               doc.open();
               doc.newPage();
               bookmarkRoot = writer.getRootOutline();
               XhtmlHandler.setBookmarkRoot(bookmarkRoot);
           }
           NavPoint fileLevelNP = Ncx.findNavPoint(ncxToc, file.getName());
           TreeNode<TocTreeNode> npNode = TocTreeNode.findInTreeByNavPoint(tocTree, fileLevelNP);
           
           if(fileLevelNP != null) {
           	doc.newPage();
           	PdfOutline pdfOutlineParent = bookmarkRoot;
           	if(npNode != null) {
           		TreeNode<TocTreeNode> parent = npNode.getParent();
           		if(parent != null) {
           			TocTreeNode parentTTN = parent.getValue();
           			if(parentTTN != null && parentTTN.getPdfOutline() != null) {
           				pdfOutlineParent = parentTTN.getPdfOutline();
           			}
           		}
           	}
           	
           	PdfDestination here = new PdfDestination(PdfDestination.FIT);
           	PdfOutline pdfTocEntry = new PdfOutline(pdfOutlineParent, here, fileLevelNP.getNavLabelText());
           	if(npNode != null) {
           		npNode.getValue().setPdfDestination(here);
           		npNode.getValue().setPdfOutline(pdfTocEntry);
           	}
           }
           XhtmlHandler.process(file.getCanonicalPath(), doc);
       }
       doc.close();
       logger.debug("PDF written to " + outputFile.getAbsolutePath());
       epubIn.cleanup();
       return outputFile;
}
 
Example 11
Source File: PurapPdf.java    From kfs with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Creates an instance of a new Document and set its margins according to
 * the given input parameters.
 *
 * @param f1  Left margin.
 * @param f2  Right margin.
 * @param f3  Top margin.
 * @param f4  Bottom margin.
 * @return    The created Document object.
 */
public Document getDocument(float f1, float f2, float f3, float f4) {
    LOG.debug("getDocument() started");
    Document document = new Document(PageSize.A4);
    // Margins: 36pt = 0.5 inch, 72pt = 1 inch. Left, right, top, bottom.
    document.setMargins(f1, f2, f3, f4);
    return document;
}