如何使用itextpdf5生成具有固定页面大小和固定内容大小的pdf

时间:2017-07-12 11:55:03

标签: java pdf itext

我想创建固定大小内容的pdf,例如,如果pdf页面大小为4/3英寸,则内容大小为4/3英寸;如果我增加pdf页面大小,内容大小应保持相同。

我有以下代码来生成pdf。

我能实现吗?如果是,那怎么??

注意:当前尺寸不适合页面小于页面尺寸。

public class PrintResource {

    private static final String PDF_FILENAME = "barcodeFile.pdf";    

    private void createConatainerPDF(String containerId) throws IOException, DocumentException {
        Document document = new Document();
        Rectangle documentSize = new Rectangle(288,216); // 4/3 inche
        document.setPageSize(documentSize); 
        document.setMargins(7,0,0,0);        
        OutputStream outputStream = null;        
        try {
            outputStream = new FileOutputStream(new File("F://Mukesh/"+PDF_FILENAME));
            PdfWriter.getInstance(document, outputStream);
            document.open();
            document.add(new Paragraph("Behaelter"));
            document.add(new Paragraph(containerId));
            Image awtImage = generatetBarcodeImage(containerId);
            //awtImage.getScaledInstance(500, 500,1);
            com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(awtImage, null);

            document.add(img);
        } finally {
            document.close();
            outputStream.close();
        }
    }

    private Image generatetBarcodeImage(String barcodeNumber) {
        Barcode128 barcode128 = new Barcode128();
        barcode128.setCode(barcodeNumber);
        barcode128.setCodeType(Barcode.CODE128);        
        barcode128.setSize(100);
        barcode128.setBarHeight(50);
        barcode128.setN(3);
        barcode128.setX(2f);

        //barcode128.setBar(100);
        return barcode128.createAwtImage(Color.BLACK, Color.WHITE);
    }

    private void deletePDFFile() {
        new File(PDF_FILENAME).delete();
    }
    public static void main(String[] args) {
        try {
            new PrintResource().createConatainerPDF("B-0000001");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) { 
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案