2018년 9월 1일 토요일

[Java] PDF Reader and Writer using PDFBox




1. PDF Reader Examples (PDFBox)

 - PDF Image Extract
 - PDF Pages to Image Converter
 - PDF Stamp


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;

public class PdfBoxTools {

    PDDocument document;
    
    public PdfBoxTools() {
    }
    
    public void load(String fileName) throws InvalidPasswordException, IOException {
        document = PDDocument.load(new File(fileName));
    }
    
    public void save(String fileName) {
        try {
            this.document.save(fileName);
            this.document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }   
    
    public void close() throws IOException {
        document.close();
    }

    public PDFont loadFont(String fontFile) {
        PDFont font = PDType1Font.HELVETICA_BOLD; 
        if( new File(fontFile).exists() ) {
            try {
                return PDType0Font.load(document, new File(fontFile));
            } catch (IOException e) {
            }
        }
        return font;
    }
        
    private int convY(PDPage page, int y) {
        return (int)page.getMediaBox().getHeight() - y - 1;
    }
        
    public PDPage newPage() throws IOException {
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage( page );
        return page;
    }   
    
    public int getPageWidth(PDPage page) {
        return (int) page.getMediaBox().getWidth();
    }
    
    public int getPageHeight(PDPage page) {
        return (int) page.getMediaBox().getHeight();
    }

    public String pageInfo() {
        PDPageTree pages = this.document.getDocumentCatalog().getPages();
        //pages.get(0);
        //this.document.getPage(0);
        //this.document.getPages();
        return "Number of Pages: " + pages.getCount();
    }
    
    //------------------------------------------------------------
    // 1. PDF Elements
    //------------------------------------------------------------
    
    //------------------------------------------------------------
    // 1.1 Text  
    //------------------------------------------------------------

    public int getTextWidth( String text, PDFont font, int fontSize ) {
        try {
            return (int)((font.getStringWidth(text)/1000)*fontSize);
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public void drawText( PDPage page, int x, int y, String text, Color color, Color bgColor, PDFont font, int fontSize ) throws IOException {
        if( font == null ) {
            font = PDType1Font.HELVETICA;
        }
        y += fontSize * 1.5;
        if( bgColor != null ) {
            int width = getTextWidth(text, font, fontSize);
            drawRect( page, new Rectangle(x,y+3,width,fontSize), bgColor, true );
        }
        PDPageContentStream stream = new PDPageContentStream( this.document, page, AppendMode.APPEND, true );
        stream.beginText();
        stream.setFont(font, fontSize);
        stream.setNonStrokingColor( color.getRed(), color.getGreen(), color.getBlue());
        stream.newLineAtOffset( x, convY(page,y) );
        stream.showText(text);
        stream.endText(); 
        stream.close();
    }
    
    public void drawText( PDPage page, int x, int y, String text, Color color ) throws IOException {
        drawText( page, x, y, text, color, null, PDType1Font.HELVETICA_BOLD, 12);
    }
    
    //------------------------------------------------------------
    // 1.2 Image  
    //------------------------------------------------------------

    public int drawImage( PDPage page, int x, int y, PDImageXObject image ) throws IOException {
        PDPageContentStream stream = new PDPageContentStream( this.document, page, AppendMode.APPEND, true );
        stream.drawImage(image, x, convY(page,y+image.getHeight()+12));
        stream.close();
        return image.getHeight()+12;
    }
    
    
    public int drawImage( PDPage page, int x, int y, String fileName ) throws IOException {
        PDImageXObject image = PDImageXObject.createFromFile(fileName, this.document);
        return drawImage( page, x, y, image);
    }

    
    //------------------------------------------------------------
    // 1.3 Polygons  
    //------------------------------------------------------------

    public void drawLine( PDPage page, int x1, int y1, int x2, int y2, int width, Color color ) throws IOException {
        PDPageContentStream stream = new PDPageContentStream( this.document, page, AppendMode.APPEND, true );
        stream.setLineWidth(width);
        stream.setStrokingColor( color.getRed(), color.getGreen(), color.getBlue());
        stream.moveTo( x1, convY(page, y1) );
        stream.lineTo( x2, convY(page, y2) );
        stream.stroke();
        stream.close();
    }

    public void drawRect( PDPage page, Rectangle rect, Color color, boolean fill) throws IOException {
        PDPageContentStream stream = new PDPageContentStream( this.document, page, AppendMode.APPEND, true );
        stream.addRect(rect.x, convY(page,(int)rect.y), rect.width, rect.height);
        if (fill) {
            stream.setNonStrokingColor(color);
            stream.fill();
        } else {
            stream.setStrokingColor(color);
            stream.stroke();
        }
        stream.close();
    }
    
    //------------------------------------------------------------
    // 2. PDF Stamp
    //------------------------------------------------------------

    public void stampTextAllPages(int x, int y, String text, Color color, Color bgColor) throws IOException {
        PDFont font = loadFont("malgunbd.ttf");
        int fontSize = 12;
        for( PDPage page : this.document.getPages() ) {         
            drawText( page, x, y, text, color, bgColor, font, fontSize );
        }
    }
    
    //------------------------------------------------------------
    // 3. PDF Image Extract
    //------------------------------------------------------------
    public void extractImagesToPng(File folder) throws IOException {
        if( folder.exists() == false ) {
            folder.mkdirs();
        }
        List<RenderedImage> images = getAllImages();
        for( int i = 0; i < images.size(); i++ ) {
            ImageIO.write( images.get(i), "png", 
                new File(folder, String.format( "image_%04d.png", i)));
        }
    }
    
    public void extractImagesToJpeg(File folder) throws IOException {
        if( folder.exists() == false ) {
            folder.mkdirs();
        }
        List<RenderedImage> images = getAllImages();
        for( int i = 0; i < images.size(); i++ ) {
            ImageIO.write( images.get(i), "jpeg", 
                new File(folder, String.format( "image_%04d.jpg", i)));
        }
    }
    
    public List<RenderedImage> getAllImages() throws IOException {
        List<RenderedImage> images = new ArrayList<>();
        for( PDPage page : document.getPages() ) {
            images.addAll(getImagesFromResources(page.getResources()));
        }
        return images;
    }
    
    private List<RenderedImage> getImagesFromResources(PDResources resources) throws IOException {
        List<RenderedImage> images = new ArrayList<>();
        for( COSName name : resources.getXObjectNames() ) {
            PDXObject obj = resources.getXObject(name);
            if (obj instanceof PDFormXObject) {
                images.addAll(getImagesFromResources(((PDFormXObject) obj).getResources()));
            } else if (obj instanceof PDImageXObject) {
                images.add(((PDImageXObject) obj).getImage());
            }
        }
        return images;
    }

    //------------------------------------------------------------
    // 4. PDF To Image Converter
    //------------------------------------------------------------
    public void convertPagesToPng(File folder) throws IOException {
        if( folder.exists() == false ) {
            folder.mkdirs();
        }
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        for( int page = 0; page < document.getNumberOfPages(); page++ ) { 
            BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);   
            ImageIOUtil.writeImage( bim, 
                String.format( folder + "/image_%04d.png", page), 300);
        }
    }
    
    public void convertPagesToJpeg(File folder) throws IOException {
        if( folder.exists() == false ) {
            folder.mkdirs();
        }
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        for( int page = 0; page < document.getNumberOfPages(); page++ ) { 
            BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);   
            ImageIOUtil.writeImage( bim, 
                String.format( folder + "/image_%04d.jpg", page), 300);
        }
    }

    //------------------------------------------------------------
    // 5. Examples
    //------------------------------------------------------------

    public static void imageExtractTest() throws IOException {
        PdfBoxTools pdf = new PdfBoxTools();
        pdf.load("D:/Ebook/python.pdf");
        pdf.extractImagesToPng(new File("D:/Temp/png"));
        pdf.extractImagesToJpeg(new File("D:/Temp/jpg"));
    }
    
    public static void imageConvertTest() throws IOException {
        PdfBoxTools pdf = new PdfBoxTools();
        pdf.load("D:/Ebook/python.pdf");
        pdf.convertPagesToPng(new File("D:/Temp/page_png"));
        pdf.convertPagesToJpeg(new File("D:/Temp/page_jpg"));
    }
        
    public static void textStamp() throws IOException {
        PdfBoxTools pdf = new PdfBoxTools();
        pdf.load("D:/document.pdf");
        pdf.stampTextAllPages(20,20,"[Confidential]",Color.RED,Color.YELLOW);
        pdf.save("D:/stamp.pdf");
    }
    
    public static void main(String[] args) throws IOException {
        System.out.println("Begin !");
        imageExtractTest();
        imageConvertTest();
        textStamp();        
        System.out.println("End !");
    }
}



2. PDF Writer Examples

 - PDF Print Text
 - PDF Print Image
 - PDF Print Line
 - PDF Print and Fill Rectangle


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import ij.IJ;
import ij.ImagePlus;
import ij.process.ImageProcessor;

public class PdfBoxPrinter extends PdfBoxTools {

    PDPage currPage;

    PDFont font;
    PDFont boldFont;
    int fontSize;

    PDRectangle pageSize;
    int topMargin;
    int bottomMargin;
    int leftMargin;
    int rightMargin;
    int currY;
    
    public PdfBoxPrinter() throws IOException {
        document = new PDDocument();

        font = PDType1Font.HELVETICA; 
        boldFont = PDType1Font.HELVETICA_BOLD; 
        fontSize = 14;

        topMargin = 72;
        bottomMargin = 72;
        leftMargin = 36;
        rightMargin = 36;

        currPage = newPage();
        currY = getTopMargin();
    }

    public void loadNormalFont(String fileName) {
        font = loadFont(fileName);
    }
    
    public void loadBoldFont(String fileName) {
        boldFont = loadFont(fileName);
    }
    
    //------------------------------------------------------------
    // 1. Pages
    //------------------------------------------------------------
    
    public int getPageContentWidth() {
        return (int)(getPageWidth(currPage) - getLeftMargin() - getRightMargin());
    }

    public int getLeftMargin() {
        return this.leftMargin;
    }

    public int getRightMargin() {
        return this.rightMargin;
    }
    
    public int getTopMargin() {
        return this.topMargin;
    }
    
    public int getBottomMargin() {
        return this.bottomMargin;
    }
    
    
    //------------------------------------------------------------
    // 2. Text Print
    //------------------------------------------------------------
    
    public void printText(String text, Color color, Color bgColor, PDFont textFont, int fontSize) throws IOException {
        List<String> lines = new ArrayList<String>();
        int width = getPageContentWidth();
        int lastSpace = -1;
        while( text.length() > 0 ) {
            int spaceIndex = text.indexOf(' ', lastSpace + 1);
            if (spaceIndex < 0) {
                spaceIndex = text.length();
            }
            String subString = text.substring(0, spaceIndex);
            float size = this.fontSize * textFont.getStringWidth(subString) / 1000;
            if( size > width ) {
                if( lastSpace < 0 ) {
                    lastSpace = spaceIndex;
                }
                subString = text.substring(0, lastSpace);
                lines.add(subString);
                text = text.substring(lastSpace).trim();
                lastSpace = -1;
            } else if( spaceIndex == text.length() ) {
                lines.add(text);
                text = "";
            } else {
                lastSpace = spaceIndex;
            }
        }

        for (String line: lines) {
            drawText( currPage, getLeftMargin(), currY, line, color, bgColor, textFont, fontSize );
            currY += this.fontSize * 1.5;
        }
    }
    
    public void printText(String text) throws IOException {     
        printText(text, Color.BLACK, null, font, fontSize );
    }
    
    public void printTextBold(String text) throws IOException {     
        printText(text, Color.BLACK, null, boldFont, fontSize );
    }

    public void printText(String text, Color color) throws IOException {        
        printText(text, color, null, font, fontSize );
    }

    public void printTextBold(String text, Color color) throws IOException {        
        printText(text, color, null, boldFont, fontSize );
    }
    
    //------------------------------------------------------------
    // 2. Text Images
    //------------------------------------------------------------
    
    public void printImage( String fileName ) throws IOException {
        ImagePlus imagePlus = IJ.openImage(fileName);
        ImageProcessor imageProc = imagePlus.getProcessor();
        int w = imageProc.getWidth();
        int h = imageProc.getHeight();
        int pageWidth = getPageContentWidth();
        if( w > pageWidth ) {
            imageProc = imageProc.resize( pageWidth, h * pageWidth / w);
        }
        BufferedImage bimage = imageProc.getBufferedImage();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write( bimage, "jpg", baos );
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();
        
        PDImageXObject image = PDImageXObject.createFromByteArray( document, imageInByte, null);
        currY +=  drawImage( currPage, getLeftMargin(), currY, image );
    }
    
    //------------------------------------------------------------
    // 3. Text Polygons
    //------------------------------------------------------------
    
    public void printLine() throws IOException {
        drawLine( currPage, getLeftMargin(), currY, 
                getPageWidth(currPage)-getRightMargin(), currY, 1, Color.BLACK );
    }

    //------------------------------------------------------------
    // 4. Examples
    //------------------------------------------------------------
    
    public static void createPdfDocument() throws IOException {
        String s = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox";
        PdfBoxPrinter pdf = new PdfBoxPrinter();
        pdf.loadNormalFont("malgun.ttf");
        pdf.loadBoldFont("malgunbd.ttf");
        pdf.printLine();
        pdf.printText(s);
        pdf.printImage("D:/image.png");
        pdf.printTextBold(s);
        pdf.printText(s, Color.RED);
        pdf.printTextBold(s, Color.BLUE);
        pdf.printText(" ");
        pdf.printLine();
        pdf.save("D:/document.pdf");
    }

    public static void main(String[] args) throws IOException {
        System.out.println("Begin !");
        createPdfDocument();
        System.out.println("End !");
    }
}

Output:






댓글 없음:

댓글 쓰기