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

项目: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);
    }
}
项目: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);
}
项目:sistra    文件:Lista.java   
public void write(PDFDocument document, PdfPTable tabla) throws DocumentException {
    com.lowagie.text.List list = new com.lowagie.text.List(false,10f);
    list.setListSymbol(new Chunk("\u2022"));

    PdfPCell cell = new PdfPCell();

    if(!titulo.equals(""))
    {
       cell.addElement(new Phrase(titulo,document.getContext().getDefaultFont()));
    }

    for(int i=0; i<campos.size(); i++)
    {
        list.add(new ListItem((String)campos.get(i),document.getContext().getDefaultFont()));
    }

    cell.addElement(list);
    cell.setPaddingLeft(30f);
    cell.setBorder(Rectangle.LEFT | Rectangle.RIGHT);
    cell.setColspan(2);
    tabla.addCell(cell);

}
项目: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();
}
项目: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();
    }

}
项目:OSCAR-ConCert    文件:EFormPDFServlet.java   
private void addDocumentProps(Document document, String title, Properties props) {
    document.addTitle(title);
    document.addSubject("");
    document.addKeywords("pdf, itext");
    document.addCreator("OSCAR");
    document.addAuthor("");

    // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA
    // and FLSE
    // the following shows a temp way to get a print page size
    final String PAGESIZE = "printPageSize";
    Rectangle pageSize = PageSize.LETTER;
    if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE)))
        pageSize = PageSize.HALFLETTER;
    if ("PageSize.A6".equals(props.getProperty(PAGESIZE)))
        pageSize = PageSize.A6;
    document.setPageSize(pageSize);
    document.open();
}
项目:itext2    文件:PdfAnnotation.java   
/**
 * Creates a screen PdfAnnotation
 * @param writer
 * @param rect
 * @param clipTitle
 * @param fs
 * @param mimeType
 * @param playOnDisplay
 * @return a screen PdfAnnotation
 * @throws IOException
 */
public static PdfAnnotation createScreen(PdfWriter writer, Rectangle rect, String clipTitle, PdfFileSpecification fs,
                                         String mimeType, boolean playOnDisplay) throws IOException {
    PdfAnnotation ann = new PdfAnnotation(writer, rect);
    ann.put(PdfName.SUBTYPE, PdfName.SCREEN);
    ann.put (PdfName.F, new PdfNumber(FLAGS_PRINT));
    ann.put(PdfName.TYPE, PdfName.ANNOT);
    ann.setPage();
    PdfIndirectReference ref = ann.getIndirectReference();
    PdfAction action = PdfAction.rendition(clipTitle,fs,mimeType, ref);
    PdfIndirectReference actionRef = writer.addToBody(action).getIndirectReference();
    // for play on display add trigger event
    if (playOnDisplay)
    {
        PdfDictionary aa = new PdfDictionary();
        aa.put(new PdfName("PV"), actionRef);
        ann.put(PdfName.AA, aa);
    }
    ann.put(PdfName.A, actionRef);
    return ann;
}
项目:itext2    文件:PdfAnnotation.java   
public static PdfAnnotation createMarkup(PdfWriter writer, Rectangle rect, String contents, int type, float quadPoints[]) {
    PdfAnnotation annot = new PdfAnnotation(writer, rect);
    PdfName name = PdfName.HIGHLIGHT;
    switch (type) {
        case MARKUP_UNDERLINE:
            name = PdfName.UNDERLINE;
            break;
        case MARKUP_STRIKEOUT:
            name = PdfName.STRIKEOUT;
            break;
        case MARKUP_SQUIGGLY:
            name = PdfName.SQUIGGLY;
            break;
    }
    annot.put(PdfName.SUBTYPE, name);
    annot.put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE));
    PdfArray array = new PdfArray();
    for (int k = 0; k < quadPoints.length; ++k)
        array.add(new PdfNumber(quadPoints[k]));
    annot.put(PdfName.QUADPOINTS, array);
    return annot;
}
项目:itext2    文件:PdfSignatureAppearance.java   
/**
 * Sets the signature to be visible. It creates a new visible signature field.
 * @param pageRect the position and dimension of the field in the page
 * @param page the page to place the field. The fist page is 1
 * @param fieldName the field name or <CODE>null</CODE> to generate automatically a new field name
 */    
public void setVisibleSignature(Rectangle pageRect, int page, String fieldName) {
    if (fieldName != null) {
        if (fieldName.indexOf('.') >= 0)
            throw new IllegalArgumentException("Field names cannot contain a dot.");
        AcroFields af = writer.getAcroFields();
        AcroFields.Item item = af.getFieldItem(fieldName);
        if (item != null)
            throw new IllegalArgumentException("The field " + fieldName + " already exists.");
        this.fieldName = fieldName;
    }
    if (page < 1 || page > writer.reader.getNumberOfPages())
        throw new IllegalArgumentException("Invalid page number: " + page);
    this.pageRect = new Rectangle(pageRect);
    this.pageRect.normalize();
    rect = new Rectangle(this.pageRect.getWidth(), this.pageRect.getHeight());
    this.page = page;
    newField = true;
}
项目:docx4j-export-FO    文件:Conversion.java   
/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
    try {
        Rectangle page = document.getPageSize();

        if (headerFooterPolicy.getHeader(writer.getPageNumber())!=null) {
         Hdr hdr = headerFooterPolicy.getHeader(writer.getPageNumber()).getJaxbElement();
         PdfPTable head = new PdfPTable(1); // num cols             
         // TODO - no cell borders
         traverseBlockLevelContent( hdr.getEGBlockLevelElts(), head);
         head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
         head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin() + head.getTotalHeight(),
             writer.getDirectContent());
        }

        if (headerFooterPolicy.getFooter(writer.getPageNumber())!=null) {
         Ftr ftr = headerFooterPolicy.getFooter(writer.getPageNumber()).getJaxbElement();               
         PdfPTable foot = new PdfPTable(1);
         traverseBlockLevelContent( ftr.getEGBlockLevelElts(), foot);
         foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
         foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
             writer.getDirectContent());
        }
    }
    catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
项目:itext2    文件:PdfCopy.java   
void applyRotation(PdfDictionary pageN, ByteBuffer out) {
    if (!cstp.rotateContents)
        return;
    Rectangle page = reader.getPageSizeWithRotation(pageN);
    int rotation = page.getRotation();
    switch (rotation) {
        case 90:
            out.append(PdfContents.ROTATE90);
            out.append(page.getTop());
            out.append(' ').append('0').append(PdfContents.ROTATEFINAL);
            break;
        case 180:
            out.append(PdfContents.ROTATE180);
            out.append(page.getRight());
            out.append(' ');
            out.append(page.getTop());
            out.append(PdfContents.ROTATEFINAL);
            break;
        case 270:
            out.append(PdfContents.ROTATE270);
            out.append('0').append(' ');
            out.append(page.getRight());
            out.append(PdfContents.ROTATEFINAL);
            break;
    }
}
项目:itext2    文件:PdfAnnotationsImp.java   
public PdfArray rotateAnnotations(PdfWriter writer, Rectangle pageSize) {
    PdfArray array = new PdfArray();
    int rotation = pageSize.getRotation() % 360;
    int currentPage = writer.getCurrentPageNumber();
    for (int k = 0; k < annotations.size(); ++k) {
        PdfAnnotation dic = (PdfAnnotation)annotations.get(k);
        int page = dic.getPlaceInPage();
        if (page > currentPage) {
            delayedAnnotations.add(dic);
            continue;
        }
        if (dic.isForm()) {
            if (!dic.isUsed()) {
                HashMap templates = dic.getTemplates();
                if (templates != null)
                    acroForm.addFieldTemplates(templates);
            }
            PdfFormField field = (PdfFormField)dic;
            if (field.getParent() == null)
                acroForm.addDocumentField(field.getIndirectReference());
        }
        if (dic.isAnnotation()) {
            array.add(dic.getIndirectReference());
            if (!dic.isUsed()) {
                PdfRectangle rect = (PdfRectangle)dic.get(PdfName.RECT);
                if (rect != null) {
                    switch (rotation) {
                        case 90:
                            dic.put(PdfName.RECT, new PdfRectangle(
                                    pageSize.getTop() - rect.bottom(),
                        rect.left(),
                        pageSize.getTop() - rect.top(),
                        rect.right()));
                            break;
                        case 180:
                            dic.put(PdfName.RECT, new PdfRectangle(
                                    pageSize.getRight() - rect.left(),
                        pageSize.getTop() - rect.bottom(),
                        pageSize.getRight() - rect.right(),
                        pageSize.getTop() - rect.top()));
                            break;
                        case 270:
                            dic.put(PdfName.RECT, new PdfRectangle(
                                    rect.bottom(),
                        pageSize.getRight() - rect.left(),
                        rect.top(),
                        pageSize.getRight() - rect.right()));
                            break;
                    }
                }
            }
        }
        if (!dic.isUsed()) {
            dic.setUsed();
            try {
                writer.addToBody(dic, dic.getIndirectReference());
            }
            catch (IOException e) {
                throw new ExceptionConverter(e);
            }
        }
    }
    return array;
}
项目: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();
}
项目:dhis2-core    文件:DefaultPdfDataEntryFormService.java   
private void addCell_WithDropDownListField( PdfPTable table, Rectangle rect, PdfWriter writer, PdfPCell cell, String strfldName, String[] optionList,
    String[] valueList ) throws IOException, DocumentException
{
    TextField textList = new TextField( writer, rect, strfldName );

    textList.setChoices( optionList );
    textList.setChoiceExports( valueList );

    textList.setBorderWidth( 1 );
    textList.setBorderColor( Color.BLACK );
    textList.setBorderStyle( PdfBorderDictionary.STYLE_SOLID );
    textList.setBackgroundColor( COLOR_BACKGROUDTEXTBOX );

    PdfFormField dropDown = textList.getComboField();

    cell.setCellEvent( new PdfFieldCell( dropDown, rect.getWidth(), rect.getHeight(), writer ) );

    table.addCell( cell );
}
项目:OSCAR-ConCert    文件:OscarChartPrinter.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();
}
项目:itext2    文件:PdfAcroForm.java   
/**
 * @param field
 * @param name
 * @param value
 * @param status
 * @param llx
 * @param lly
 * @param urx
 * @param ury
 */
public void setCheckBoxParams(PdfFormField field, String name, String value, boolean status, float llx, float lly, float urx, float ury) {
    field.setWidget(new Rectangle(llx, lly, urx, ury), PdfAnnotation.HIGHLIGHT_TOGGLE);
    field.setFieldName(name);
    if (status) {
        field.setValueAsName(value);
        field.setAppearanceState(value);
    }
    else {
        field.setValueAsName("Off");
        field.setAppearanceState("Off");
    }
    field.setFlags(PdfAnnotation.FLAGS_PRINT);
    field.setPage();
    field.setBorderStyle(new PdfBorderDictionary(1, PdfBorderDictionary.STYLE_SOLID));
}
项目:OSCAR-ConCert    文件:TicklerPrinter.java   
public void footer() {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    Date now = new Date();
    String promoTxt = OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT");
    if (promoTxt == null) {
        promoTxt = new String();
    }

    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();
}
项目:itext2    文件:PdfTemplate.java   
/**
 * Gets a duplicate of this <CODE>PdfTemplate</CODE>. All
 * the members are copied by reference but the buffer stays different.
 * @return a copy of this <CODE>PdfTemplate</CODE>
 */

public PdfContentByte getDuplicate() {
    PdfTemplate tpl = new PdfTemplate();
    tpl.writer = writer;
    tpl.pdf = pdf;
    tpl.thisReference = thisReference;
    tpl.pageResources = pageResources;
    tpl.bBox = new Rectangle(bBox);
    tpl.group = group;
    tpl.layer = layer;
    if (matrix != null) {
        tpl.matrix = new PdfArray(matrix);
    }
    tpl.separator = separator;
    return tpl;
}
项目:itext2    文件:RtfBorderGroup.java   
/**
 * Adds borders to the RtfBorderGroup
 * 
 * @param bordersToAdd The borders to add (Rectangle.LEFT, Rectangle.RIGHT, Rectangle.TOP, Rectangle.BOTTOM, Rectangle.BOX)
 * @param borderStyle The style of border to add (from RtfBorder)
 * @param borderWidth The border width to use
 * @param borderColor The border color to use
 */
public void addBorder(int bordersToAdd, int borderStyle, float borderWidth, Color borderColor) {
    if((bordersToAdd & Rectangle.LEFT) == Rectangle.LEFT) {
        setBorder(RtfBorder.LEFT_BORDER, borderStyle, borderWidth, borderColor);
    }
    if((bordersToAdd & Rectangle.TOP) == Rectangle.TOP) {
        setBorder(RtfBorder.TOP_BORDER, borderStyle, borderWidth, borderColor);
    }
    if((bordersToAdd & Rectangle.RIGHT) == Rectangle.RIGHT) {
        setBorder(RtfBorder.RIGHT_BORDER, borderStyle, borderWidth, borderColor);
    }
    if((bordersToAdd & Rectangle.BOTTOM) == Rectangle.BOTTOM) {
        setBorder(RtfBorder.BOTTOM_BORDER, borderStyle, borderWidth, borderColor);
    }
    if((bordersToAdd & Rectangle.BOX) == Rectangle.BOX && this.borderType == RtfBorder.ROW_BORDER) {
        setBorder(RtfBorder.VERTICAL_BORDER, borderStyle, borderWidth, borderColor);
        setBorder(RtfBorder.HORIZONTAL_BORDER, borderStyle, borderWidth, borderColor);
    }
}
项目:itext2    文件:RtfBorderGroup.java   
/**
 * Removes borders from the list of borders
 * 
 * @param bordersToRemove The borders to remove (from Rectangle)
 */
public void removeBorder(int bordersToRemove) {
    if((bordersToRemove & Rectangle.LEFT) == Rectangle.LEFT) {
        this.borders.remove(Integer.valueOf(RtfBorder.LEFT_BORDER));
    }
    if((bordersToRemove & Rectangle.TOP) == Rectangle.TOP) {
        this.borders.remove(Integer.valueOf(RtfBorder.TOP_BORDER));
    }
    if((bordersToRemove & Rectangle.RIGHT) == Rectangle.RIGHT) {
        this.borders.remove(Integer.valueOf(RtfBorder.RIGHT_BORDER));
    }
    if((bordersToRemove & Rectangle.BOTTOM) == Rectangle.BOTTOM) {
        this.borders.remove(Integer.valueOf(RtfBorder.BOTTOM_BORDER));
    }
    if((bordersToRemove & Rectangle.BOX) == Rectangle.BOX && this.borderType == RtfBorder.ROW_BORDER) {
        this.borders.remove(Integer.valueOf(RtfBorder.VERTICAL_BORDER));
        this.borders.remove(Integer.valueOf(RtfBorder.HORIZONTAL_BORDER));
    }
}
项目:unitimes    文件:PDFPrinter.java   
@Override
public void printHeader(String... fields) {
    iTable = new PdfPTable(fields.length - iHiddenColumns.size());
    iMaxWidth = new float[fields.length];
    iTable.setHeaderRows(1);
    iTable.setWidthPercentage(100);

    for (int idx = 0; idx < fields.length; idx++) {
        if (iHiddenColumns.contains(idx)) continue;
        String f = fields[idx];

        PdfPCell cell = new PdfPCell();
        cell.setBorder(Rectangle.BOTTOM);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);

        Font font = PdfFont.getFont(true);
        Paragraph ch = new Paragraph(f, font);
        ch.setLeading(0f, 1f);
        cell.addElement(ch);        
        iTable.addCell(cell);

        float width = 0; 
        if (f.indexOf('\n')>=0) {
            for (StringTokenizer s = new StringTokenizer(f,"\n"); s.hasMoreTokens();)
                width = Math.max(width,font.getBaseFont().getWidthPoint(s.nextToken(), font.getSize()));
        } else 
            width = Math.max(width,font.getBaseFont().getWidthPoint(f, font.getSize()));
        iMaxWidth[idx] = width;
    }
}
项目:jaffa-framework    文件:FormPrintEngineIText.java   
/**
 * Any work to start off printing a page of the document
 * m_currentPage will contain the page being printed, and
 * m_currentTemplatePage will contain the template page number to base this
 * new page on.
 * @throws FormPrintException Thrown if there is any form processing problems
 */
protected void startPage() throws FormPrintException {
    log.debug("startPage: Page=" + getCurrentPage());

    Rectangle r = m_templateReader.getPageSize(getCurrentTemplatePage());
    log.debug( "Page Size      : t="+r.getTop()+",l="+r.getLeft()+",b="+r.getBottom()+",r="+r.getRight()+", rot="+r.getRotation() );
    r = m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage());
    log.debug( "Page Size w/Rot: t="+r.getTop()+",l="+r.getLeft()+",b="+r.getBottom()+",r="+r.getRight()+", rot="+r.getRotation() );

    // Get rotation quadrent 0..3
    int q = (m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()).getRotation() % 360)/90;
    float tX = (q==2?r.getTop():0)+(q==3?r.getRight():0);
    float tY = (q==1?r.getTop():0)+(q==2?r.getRight():0);
    float sX=1f, sY=1f;
    double angle = -r.getRotation()*(Math.PI/180f);
    double transformA = sX * Math.cos(angle);
    double transformB = sY * Math.sin(angle);
    double transformC = -sX * Math.sin(angle);
    double transformD = sY * Math.cos(angle);
    double transformE = tX;
    double transformF = tY;


    m_generatedDoc.setPageSize(m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()) );
    //m_generatedDoc.setPageSize(m_templateReader.getPageSize(getCurrentTemplatePage()) );
    /**
     * try {
     * m_generatedDoc.newPage();
     * } catch (DocumentException e) {
     * log.error("Error Creating New Page - " + e.getMessage() ,e);
     * throw new EngineProcessingException("Error Creating New Page - " + e.getMessage());
     * }
     **/
    m_generatedDoc.newPage();

    PdfImportedPage page = m_writer.getImportedPage(m_templateReader, getCurrentTemplatePage() );
    PdfContentByte cb = m_writer.getDirectContent();
    //cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
    cb.addTemplate(page, (float)transformA, (float)transformB, (float)transformC,
                         (float)transformD, (float)transformE, (float)transformF);
    log.debug("Matrix = [A=" + transformA +", B=" + transformB +", C=" + transformC +
                      ", D=" + transformD +", E=" + transformE +", F=" + transformF +" ]");
}
项目:doctemplate    文件:PDFMergeEngine.java   
private void insertImage(Image img, PdfContentByte canvas, float[] imgPosition) throws Exception {

        com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img.getBytes());

        float fieldLx = imgPosition[1];
        float fieldLy = imgPosition[2];
        float fieldUx = imgPosition[3];
        float fieldUy = imgPosition[4];
        Rectangle rect = new Rectangle(fieldLx, fieldLy, fieldUx, fieldUy);
        float absPosWidth = fieldLx;
        float absPosHeight = fieldLy;
        image.scaleToFit(rect.getWidth(), rect.getHeight());
        image.setAbsolutePosition(absPosWidth, absPosHeight);
        canvas.addImage(image, rect.getWidth(), 0, 0, rect.getHeight(), absPosWidth, absPosHeight);
    }
项目:itext2    文件:FormPushButtonTest.java   
/**
 * Generates an Acroform with a PushButton
 */
@Test
public void main() throws Exception {

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

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

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

    // step 4:
    PdfFormField pushbutton = PdfFormField.createPushButton(writer);
    PdfContentByte cb = writer.getDirectContent();
    cb.moveTo(0, 0);
    PdfAppearance normal = cb.createAppearance(100, 50);
    normal.setColorFill(Color.GRAY);
    normal.rectangle(5, 5, 90, 40);
    normal.fill();
    PdfAppearance rollover = cb.createAppearance(100, 50);
    rollover.setColorFill(Color.RED);
    rollover.rectangle(5, 5, 90, 40);
    rollover.fill();
    PdfAppearance down = cb.createAppearance(100, 50);
    down.setColorFill(Color.BLUE);
    down.rectangle(5, 5, 90, 40);
    down.fill();
    pushbutton.setFieldName("PushMe");
    pushbutton.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, normal);
    pushbutton.setAppearance(PdfAnnotation.APPEARANCE_ROLLOVER, rollover);
    pushbutton.setAppearance(PdfAnnotation.APPEARANCE_DOWN, down);
    pushbutton.setWidget(new Rectangle(100, 700, 200, 750), PdfAnnotation.HIGHLIGHT_PUSH);
    writer.addAnnotation(pushbutton);

    // step 5: we close the document
    document.close();
}
项目:itext2    文件:PdfAnnotation.java   
/**
 * @param writer
 * @param rect
 * @param title
 * @param contents
 * @param open
 * @param icon
 * @return a PdfAnnotation
 */
public static PdfAnnotation createText(PdfWriter writer, Rectangle rect, String title, String contents, boolean open, String icon) {
    PdfAnnotation annot = new PdfAnnotation(writer, rect);
    annot.put(PdfName.SUBTYPE, PdfName.TEXT);
    if (title != null)
        annot.put(PdfName.T, new PdfString(title, PdfObject.TEXT_UNICODE));
    if (contents != null)
        annot.put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE));
    if (open)
        annot.put(PdfName.OPEN, PdfBoolean.PDFTRUE);
    if (icon != null) {
        annot.put(PdfName.NAME, new PdfName(icon));
    }
    return annot;
}
项目:itext2    文件:PdfAnnotation.java   
/**
 * Creates a link.
 * @param writer
 * @param rect
 * @param highlight
 * @return A PdfAnnotation
 */
protected static PdfAnnotation createLink(PdfWriter writer, Rectangle rect, PdfName highlight) {
    PdfAnnotation annot = new PdfAnnotation(writer, rect);
    annot.put(PdfName.SUBTYPE, PdfName.LINK);
    if (!highlight.equals(HIGHLIGHT_INVERT))
        annot.put(PdfName.H, highlight);
    return annot;
}
项目:itext2    文件:PdfAnnotation.java   
/**
 * Adds a line to the document. Move over the line and a tooltip is shown.
 * @param writer
 * @param rect
 * @param contents
 * @param x1
 * @param y1
 * @param x2
 * @param y2
 * @return A PdfAnnotation
 */
public static PdfAnnotation createLine(PdfWriter writer, Rectangle rect, String contents, float x1, float y1, float x2, float y2) {
    PdfAnnotation annot = new PdfAnnotation(writer, rect);
    annot.put(PdfName.SUBTYPE, PdfName.LINE);
    annot.put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE));
    PdfArray array = new PdfArray(new PdfNumber(x1));
    array.add(new PdfNumber(y1));
    array.add(new PdfNumber(x2));
    array.add(new PdfNumber(y2));
    annot.put(PdfName.L, array);
    return annot;
}
项目:sistra    文件:Tabla.java   
private void addTabla(PdfPTable tablaParent, PdfPTable tabla)
{
    PdfPCell cell = new PdfPCell(tabla);
    cell.setColspan(4);
    cell.setBorder(Rectangle.NO_BORDER);
    tablaParent.addCell(cell);
}
项目:itext2    文件:PdfAnnotation.java   
/** Creates a file attachment annotation
 * @param writer
 * @param rect
 * @param contents
 * @param fs
 * @return the annotation
 * @throws IOException
 */
public static PdfAnnotation createFileAttachment(PdfWriter writer, Rectangle rect, String contents, PdfFileSpecification fs) throws IOException {
    PdfAnnotation annot = new PdfAnnotation(writer, rect);
    annot.put(PdfName.SUBTYPE, PdfName.FILEATTACHMENT);
    if (contents != null)
        annot.put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE));
    annot.put(PdfName.FS, fs.getReference());
    return annot;
}
项目:itext2    文件:PdfAnnotation.java   
public PdfAnnotation createAnnotation(PdfWriter writer) {
    PdfAnnotation annotation = new PdfAnnotation(writer, new Rectangle(llx, lly, urx, ury));
    if (newPage != 0) {
        PdfIndirectReference ref = writer.getPageReference(newPage);
        destination.set(0, ref);
    }
    if (destination != null) annotation.put(PdfName.DEST, destination);
    annotation.hashMap.putAll(parameters);
    return annotation;
}
项目:itext2    文件:PdfPTable.java   
/**
 * Sets the percentage width of the table from the absolute column width.
 * 
 * @param columnWidth the absolute width of each column
 * @param pageSize the page size
 * @throws DocumentException
 */    
public void setWidthPercentage(float columnWidth[], Rectangle pageSize) throws DocumentException {
    if (columnWidth.length != getNumberOfColumns())
        throw new IllegalArgumentException("Wrong number of columns.");
    float totalWidth = 0;
    for (int k = 0; k < columnWidth.length; ++k)
        totalWidth += columnWidth[k];
    widthPercentage = totalWidth / (pageSize.getRight() - pageSize.getLeft()) * 100f;
    setWidths(columnWidth);
}
项目:itext2    文件:PdfStamperImp.java   
private static void moveRectangle(PdfDictionary dic2, PdfReader r, int pageImported, PdfName key, String name) {
    Rectangle m = r.getBoxSize(pageImported, name);
    if (m == null)
        dic2.remove(key);
    else
        dic2.put(key, new PdfRectangle(m));
}
项目:itext2    文件:CellEventsTest.java   
/**
 * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell,
 *      com.lowagie.text.Rectangle, com.lowagie.text.pdf.PdfContentByte[])
 */
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
    PdfContentByte cb = canvases[PdfPTable.TEXTCANVAS];
    cb.moveTo(position.getLeft(), position.getBottom());
    cb.lineTo(position.getRight(), position.getTop());
    cb.stroke();
}
项目:itext2    文件:PdfCopy.java   
/**
 * Adds a blank page.
 * @param   rect The page dimension
 * @param   rotation The rotation angle in degrees
 * @since   2.1.5
 */
public void addPage(Rectangle rect, int rotation) {
    PdfRectangle mediabox = new PdfRectangle(rect, rotation);
    PageResources resources = new PageResources();
    PdfPage page = new PdfPage(mediabox, new HashMap(), resources.getResources(), 0);
    page.put(PdfName.TABS, getTabs());
    root.addPage(page);
    ++currentPageNumber;
}
项目:itext2    文件:JFreeChartTest.java   
/**
  * Converts a JFreeChart to PDF syntax.
  * @param filename the name of the PDF file
  * @param chart        the JFreeChart
  * @param width        the width of the resulting PDF
  * @param height   the height of the resulting PDF
  */
 public static void convertToPdf(JFreeChart chart, int width, int height, String filename) {
    // step 1
    Document document = new Document(new Rectangle(width, height));
    try {
        // step 2
        PdfWriter writer;
writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream(filename));
// step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        tp.sanityCheck();
        cb.addTemplate(tp, 0, 0);
        cb.sanityCheck();
    }
    catch(DocumentException de) {
        de.printStackTrace();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // step 5
    document.close();
 }
项目:jasperreports    文件:TextInputElementPdfHandler.java   
@Override
    public void exportElement(JRPdfExporterContext exporterContext, JRGenericPrintElement element)
    {
        PdfWriter writer = exporterContext.getPdfWriter();
        JasperPrint jasperPrint = exporterContext.getExportedReport();

        JRPrintText printText = (JRPrintText)element.getParameterValue(TextInputElement.PARAMETER_PRINT_TEXT_ELEMENT);
        if (printText == null) //FIXMEINPUT deal with xml serialization
        {
            return;
        }

        Rectangle rectangle = new Rectangle(
                element.getX() + exporterContext.getOffsetX(),
                jasperPrint.getPageHeight() - element.getY() - exporterContext.getOffsetY(),
                element.getX() + exporterContext.getOffsetX() + element.getWidth(),
                jasperPrint.getPageHeight() - element.getY() - exporterContext.getOffsetY() - element.getHeight()
                );
        TextField text = new TextField(writer, rectangle, getFieldName(element));
        Color backColor = printText.getBackcolor();
        if(backColor != null){
            text.setBackgroundColor(backColor);
        }
        Color forecolor = printText.getForecolor();
        if(forecolor != null){
            text.setTextColor(forecolor);
        }
        text.setText(printText.getFullText());
        text.setDefaultText("default:" + printText.getFullText());
//      text.setBackgroundColor(element.getBackcolor());
//      text.setTextColor(element.getForecolor());
//      text.setText(getText(element));
//      text.setDefaultText(getDefaultText(element));

        //FIXME: dynamic settings below:

//      text.setAlignment(Element.ALIGN_LEFT);
//      text.setBorderColor(Color.BLACK);
//      text.setBorderWidth(TextField.BORDER_WIDTH_THIN);
//      text.setBorderStyle(PdfBorderDictionary.STYLE_INSET);

//      text.setChoiceExports(null);
//      text.setChoices(null);
//      text.setChoiceSelection(0);
//      text.setExtensionFont(null);
//      text.setExtraMargin(0, 0);
//      try{
//          text.setFont(BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1250, true));
//      }catch(Exception e){
//          throw new JRRuntimeException(e);
//      }
        text.setFontSize(printText.getFontsize());
        if (Boolean.TRUE.equals(element.getParameterValue(TextInputElement.PARAMETER_MULTI_LINE)))
        {
            text.setOptions(TextField.MULTILINE);
        }
//      text.setRotation(90);
        text.setVisibility(TextField.VISIBLE);

        try{
            PdfFormField field = text.getTextField();
            writer.addAnnotation(field);
        }catch(Exception e){
            throw new JRRuntimeException(e);
        }

    }
项目:dhis2-core    文件:DefaultPdfDataEntryFormService.java   
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 );
    }
}
项目:sistra    文件:Tabla.java   
private PdfPCell createCell(String texto)
{
    PdfPCell cell = new PdfPCell(new Phrase(texto));
    cell.setPaddingLeft(10f);
    cell.setHorizontalAlignment(Rectangle.LEFT);
    //this.tabla.addCell(cell);
    return cell;
}
项目:erp    文件:ImprimeOS.java   
public boolean gravaPdf(File fArq) {

        Rectangle pageSize = new Rectangle(PageSize.A4);
        Document document = new Document(pageSize);

        try {

            PdfWriter.getInstance(document, new FileOutputStream(fArq));
            document.addTitle(sTitulo);
            document.open();

            Font font = FontFactory.getFont(FontFactory.COURIER, 6, Font.NORMAL, Color.black);

            for (int i = 1; i <= getNumPags(); ++i) {

                Paragraph paragrafo = new Paragraph(lePagina(i), font);
                document.add(paragrafo);

                if (bImpEject) {
                    document.newPage();
                }
            }
        }
        catch (DocumentException de) {
            System.err.println(de.getMessage());
        }
        catch (Exception ioe) {
            System.err.println(ioe.getMessage());
        }
        document.close();

        return true;
    }