2014년 3월 25일 화요일

[Android] iTextPdf 사용하기.

1 ITextG

# License 관련 : AGPL 라이센스로, 라이브러리를 사용하면 코드를 공개해야 함.

2 iTextG

-  iTextG를 사용하기 위해 libs에 itextg-5.5.0.jar 를 추가한다.

3. Code 사용

public class HelloWorldDirect {
 
    /** Path to the resulting PDF file. */
    public static final String RESULT
        = "results/part1/chapter01/hello_direct.pdf";
 
    /** * Creates a PDF file: hello_direct.pdf * @param args no arguments needed */
    public static void main(String[] args)
        throws DocumentException, IOException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer =
            PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        PdfContentByte canvas = writer.getDirectContentUnder();
        writer.setCompressionLevel(0);
        canvas.saveState();                               // q
        canvas.beginText();                               // BT
        canvas.moveText(36, 788);                         // 36 788 Td
        canvas.setFontAndSize(BaseFont.createFont(), 12); // /F1 12 Tf
        canvas.showText("Hello World");                   // (Hello World)Tj
        canvas.endText();                                 // ET
        canvas.restoreState();                            // Q
        // step 5
        document.close();
    }
}
public class ImageDirect {
 
    /** The resulting PDF. */
    public static final String RESULT
        = "results/part1/chapter03/image_direct.pdf";
    /** The movie poster. */
    public static final String RESOURCE
        = "resources/img/loa.jpg";
 
    public static void main(String[] args)
        throws IOException, DocumentException {
     // step 1
        Document document
            = new Document(PageSize.POSTCARD, 30, 30, 30, 30);
        // step 2
        PdfWriter writer
            = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        writer.setCompressionLevel(0);
        // step 3
        document.open();
        // step 4
        Image img = Image.getInstance(RESOURCE);
        img.setAbsolutePosition((PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2,
                (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2);
        writer.getDirectContent().addImage(img);
        Paragraph p = new Paragraph("Foobar Film Festival", new Font(FontFamily.HELVETICA, 22));
        p.setAlignment(Element.ALIGN_CENTER);
        document.add(p);
        // step 5
        document.close();
    }
}
이미지 Scale 조정
public static final String 222 = "/mnt/sdcard/222";
public static final String RESULT =2222 + "/image_direct.pdf";
Image img = Image.getInstance(RESOURCE);
img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());

4. Sample Project


댓글 없음:

댓글 쓰기