그림과 텍스트를 pdf 파일에 쓰기
iText는 현재 bmp 형식의 그림을 지원하지 않기 때문에 pdf에 삽입할 때 변환해야 합니다.
변환 코드
- package com.taiji.lbs.register.util;
-
- import java.awt.Image;
- import java.awt.Toolkit;
- import java.awt.image.BufferedImage;
- import java.awt.image.MemoryImageSource;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import com.sun.image.codec.jpeg.JPEGCodec;
- import com.sun.image.codec.jpeg.JPEGImageEncoder;
-
- public class BmpToJpg {
-
- /**
- * BMP -> JPG
- * @param file
- * @param dstFile
- */
- public static void bmpTojpg(String file, String dstFile) {
- try {
- FileInputStream in = new FileInputStream(file);
- Image TheImage = read(in);
- int wideth = TheImage.getWidth(null);
- int height = TheImage.getHeight(null);
- BufferedImage tag = new BufferedImage(wideth, height,BufferedImage.TYPE_INT_RGB);
- tag.getGraphics().drawImage(TheImage, 0, 0, wideth, height, null);
- FileOutputStream out = new FileOutputStream(dstFile);
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
- encoder.encode(tag);
- out.close();
- } catch (Exception e) {
- System.out.println(e);
- }
- }
-
- public static int constructInt(byte[] in, int offset) {
- int ret = ((int) in[offset + 3] & 0xff);
- ret = (ret << 8) | ((int) in[offset + 2] & 0xff);
- ret = (ret << 8) | ((int) in[offset + 1] & 0xff);
- ret = (ret << 8) | ((int) in[offset + 0] & 0xff);
- return (ret);
- }
-
- public static int constructInt3(byte[] in, int offset) {
- int ret = 0xff;
- ret = (ret << 8) | ((int) in[offset + 2] & 0xff);
- ret = (ret << 8) | ((int) in[offset + 1] & 0xff);
- ret = (ret << 8) | ((int) in[offset + 0] & 0xff);
- return (ret);
- }
-
- public static long constructLong(byte[] in, int offset) {
- long ret = ((long) in[offset + 7] & 0xff);
- ret |= (ret << 8) | ((long) in[offset + 6] & 0xff);
- ret |= (ret << 8) | ((long) in[offset + 5] & 0xff);
- ret |= (ret << 8) | ((long) in[offset + 4] & 0xff);
- ret |= (ret << 8) | ((long) in[offset + 3] & 0xff);
- ret |= (ret << 8) | ((long) in[offset + 2] & 0xff);
- ret |= (ret << 8) | ((long) in[offset + 1] & 0xff);
- ret |= (ret << 8) | ((long) in[offset + 0] & 0xff);
- return (ret);
- }
-
- public static double constructDouble(byte[] in, int offset) {
- long ret = constructLong(in, offset);
- return (Double.longBitsToDouble(ret));
- }
-
- public static short constructShort(byte[] in, int offset) {
- short ret = (short) ((short) in[offset + 1] & 0xff);
- ret = (short) ((ret << 8) | (short) ((short) in[offset + 0] & 0xff));
- return (ret);
- }
-
- static class BitmapHeader {
- public int iSize, ibiSize, iWidth, iHeight, iPlanes, iBitcount,
- iCompression, iSizeimage, iXpm, iYpm, iClrused, iClrimp;
-
- // bmp
- public void read(FileInputStream fs) throws IOException {
- final int bflen = 14;
- byte bf[] = new byte[bflen];
- fs.read(bf, 0, bflen);
- final int bilen = 40;
- byte bi[] = new byte[bilen];
- fs.read(bi, 0, bilen);
- iSize = constructInt(bf, 2);
- ibiSize = constructInt(bi, 2);
- iWidth = constructInt(bi, 4);
- iHeight = constructInt(bi, 8);
- iPlanes = constructShort(bi, 12);
- iBitcount = constructShort(bi, 14);
- iCompression = constructInt(bi, 16);
- iSizeimage = constructInt(bi, 20);
- iXpm = constructInt(bi, 24);
- iYpm = constructInt(bi, 28);
- iClrused = constructInt(bi, 32);
- iClrimp = constructInt(bi, 36);
- }
- }
-
- public static Image read(FileInputStream fs) {
- try {
- BitmapHeader bh = new BitmapHeader();
- bh.read(fs);
- if (bh.iBitcount == 24) {
- return (readImage24(fs, bh));
- }
- if (bh.iBitcount == 32) {
- return (readImage32(fs, bh));
- }
- fs.close();
- } catch (IOException e) {
- System.out.println(e);
- }
- return (null);
- }
-
- // 24
- protected static Image readImage24(FileInputStream fs, BitmapHeader bh)
- throws IOException {
- Image image;
- if (bh.iSizeimage == 0) {
- bh.iSizeimage = ((((bh.iWidth * bh.iBitcount) + 31) & ~31) >> 3);
- bh.iSizeimage *= bh.iHeight;
- }
- int npad = (bh.iSizeimage / bh.iHeight) - bh.iWidth * 3;
- int ndata[] = new int[bh.iHeight * bh.iWidth];
- byte brgb[] = new byte[(bh.iWidth + npad) * 3 * bh.iHeight];
- fs.read(brgb, 0, (bh.iWidth + npad) * 3 * bh.iHeight);
- int nindex = 0;
- for (int j = 0; j < bh.iHeight; j++) {
- for (int i = 0; i < bh.iWidth; i++) {
- ndata[bh.iWidth * (bh.iHeight - j - 1) + i] = constructInt3(
- brgb, nindex);
- nindex += 3;
- }
- nindex += npad;
- }
- image = Toolkit.getDefaultToolkit().createImage(
- new MemoryImageSource(bh.iWidth, bh.iHeight, ndata, 0,
- bh.iWidth));
- fs.close();
- return (image);
- }
-
- // 32
- protected static Image readImage32(FileInputStream fs, BitmapHeader bh)
- throws IOException {
- Image image;
- int ndata[] = new int[bh.iHeight * bh.iWidth];
- byte brgb[] = new byte[bh.iWidth * 4 * bh.iHeight];
- fs.read(brgb, 0, bh.iWidth * 4 * bh.iHeight);
- int nindex = 0;
- for (int j = 0; j < bh.iHeight; j++) {
- for (int i = 0; i < bh.iWidth; i++) {
- ndata[bh.iWidth * (bh.iHeight - j - 1) + i] = constructInt3(
- brgb, nindex);
- nindex += 4;
- }
- }
- image = Toolkit.getDefaultToolkit().createImage(
- new MemoryImageSource(bh.iWidth, bh.iHeight, ndata, 0,
- bh.iWidth));
- fs.close();
- return (image);
- }
-
- public static void main(String[] args) {
- String srcfile = "c:\\726.bmp";
- String dstFile = "c:\\726.jpg";
- bmpTojpg(srcfile, dstFile);
- }
-
- }
코드 삽입을 보도록 하겠습니다.
- package com.taiji.lbs.register.util;
-
- import java.io.ByteArrayInputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.util.List;
-
- import com.lowagie.text.Document;
- import com.lowagie.text.DocumentException;
- import com.lowagie.text.Image;
- import com.lowagie.text.Paragraph;
- import com.lowagie.text.pdf.BaseFont;
- import com.lowagie.text.pdf.PdfWriter;
- import com.taiji.core.util.ApplicationPath;
- import com.taiji.core.util.PaginationSupport;
- import com.taiji.lbs.register.hibernate.model.Picture;
- import com.taiji.lbs.register.hibernate.model.RegisterInfo;
-
- public class CreatePDF {
- /**
- * pdf
- *
- * @param list
- * @throws DocumentException
- * @throws Exception
- */
- public static void createPDF(PaginationSupport list) throws Exception, DocumentException{
- // pdf
- List pdfList = list.getItems();
- String picName = "";
- String picNameDst = "";// bmp jpg
- String str = "";
- String rootPath = ApplicationPath.getRootPath().replaceAll("\\\\","\\\\\\\\");//
- //
- Document doc = new Document();
- PdfWriter.getInstance(doc, new FileOutputStream("c:/hello.pdf"));
- //
- doc.open();
- // , windos
- BaseFont basefont;
- com.lowagie.text.Font FontChinese ;
- basefont = BaseFont.createFont("c:\\windows\\fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
- FontChinese = new com.lowagie.text.Font(basefont);
- for (Object object : pdfList) {
- Picture pic = ((RegisterInfo)object).getPicture();
- if (pic != null) {
- picName = String.valueOf(pic.getId() + ".bmp");
- picNameDst = String.valueOf(pic.getId() + ".jpg");
- File filePic = new File(rootPath + "\\photo\\" + picName);
- FileOutputStream output;
- output = new FileOutputStream(filePic);
- byte buffer[] = null;
- if (pic.getPhoto() != null) {
- buffer = pic.getPhoto();
- InputStream in = new ByteArrayInputStream(buffer);
- int len;
- while ((len = in.read(buffer)) > 0) {
- output.write(buffer, 0, len);
- }
- output.close();
- in.close();
- } else {
- picName = null;
- }
- }
- BmpToJpg.bmpTojpg(rootPath + "\\photo\\" + picName, rootPath + "\\photo\\" + picNameDst);
- //
- Image jpg = Image.getInstance(rootPath + "\\photo\\" + picNameDst);
- jpg.setAlignment(Image.ALIGN_LEFT);
- doc.add(jpg);
- //
- str = ((RegisterInfo)object).getId()+":"+((RegisterInfo)object).getIdNum();
- Paragraph tt = new Paragraph(str, FontChinese);
- tt.setAlignment(Paragraph.ALIGN_CENTER);
- doc.add(tt);
- }
- //
- doc.close();
- }
- }
이렇게 하면 그림 형식의 변환과 삽입이 완성되었다.
===============================================================
이전의 그 예는 그림과 텍스트가 쉽게 분리된다. 더욱 보기 좋게 그림과 텍스트를 한 표에 넣기 위해 일부 코드를 다음과 같이 수정한다.
- BmpToJpg.bmpTojpg(rootPath + "\\photo\\" + picName, rootPath + "\\photo\\" + picNameDst);
- //
- Image jpg = Image.getInstance(rootPath + "\\photo\\" + picNameDst);
- jpg.setAlignment(Image.ALIGN_LEFT);
- //doc.add(jpg);
- //
- str = ((RegisterInfo)object).getChineseName()+" "+((RegisterInfo)object).getEnglishName()+" "+((RegisterInfo)object).getNationality()+" "+((RegisterInfo)object).getIdNum()+" "+((RegisterInfo)object).getDiplomaticTitle();
- Paragraph tt = new Paragraph(str, FontChinese);
- tt.setAlignment(Paragraph.ALIGN_RIGHT);
- //doc.add(tt);
-
-
- // 1
- PdfPTable table = new PdfPTable(1);
- //
- PdfPCell cell = new PdfPCell(jpg);
- //
- table.addCell(cell);
- //
- PdfPCell cellText = new PdfPCell(tt);
- //
- table.addCell(cellText);
- //
- doc.add(table);
본문 은 '조레이 의 블로그 학습 진보' 블로그 에서 나온 것 이니, 반드시 이 출처 를 보존해 주십시오http://sucre.blog.51cto.com/1084905/554921
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
양식 제출 후 제출 버튼 비활성화텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.