用PDFBox从PDF中提取图片

从PDF文件中提取图片,这个也用到了PDFBox。
将图片提取出来,PDF每一页中有多个图片时也可以提取出每个图片。

提取后发现有部分有带透明的图片提取后会有两个图片,一个有透明,一个背景为黑色,这个黑色背景的图片并不需要,要把它删掉。

于是将提取的图片分为两组,一组有透明的,一组没透明的。
再将透明的图片加上黑色背景,后与没透明的那组图片进行比较,相同的即是多余出来带黑色背景的图片,把它删掉,剩下的就是提取所要的图片了。
继续阅读“用PDFBox从PDF中提取图片”

iText生成PDF在PdfTemplate中设置文字加粗,斜体

iText 生成PDF在PdfTemplate中设置文字加粗,斜体

由于PdfTemplate继承于PdfContentByte类,可以使用PdfContentByte方法来进行操作

Document doc = new Document();
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filepath));
doc.open();
PdfContentByte cb = writer.getDirectContent();

创建template并加到PdfContentByte里,template的状态位置是采用matrix方式来设置

PdfTemplate template = cb.createTemplate(width, height);
cb.addTemplate(template, 1f, 0f, 0f, 1f, 0f, 0f);

继续阅读“iText生成PDF在PdfTemplate中设置文字加粗,斜体”

java html转图片,并设置透明背景

在谷歌上可以找到的java库html2image,直接可将html内容转为image保存起来
http://java-html2image.googlecode.com/files/html2image-0.9.jar
简单的例子如下

import gui.ava.html.image.generator.HtmlImageGenerator;

public class txt2img {

    public static void main(String[] args) throws Exception {
        String text    = args[0];
        String filename    = args[1];

        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        imageGenerator.loadHtml(text);
        imageGenerator.getBufferedImage();
        imageGenerator.saveAsImage(filename);
    }
}

不过生成图片后发现,图片背景是白色的,但我只需要内容,要透明的背景。
继续阅读“java html转图片,并设置透明背景”

java itext添加中文文字和设置文字颜色

java itext添加中文文字和设置文字颜色
下面是示例代码

import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;

import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.BaseColor;


public class Test {
	public static void main(String[] args) {
		Rectangle pSize = new Rectangle(300, 400);
		Document doc = new Document(pSize); //创建文档

		try {
			PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("testpdf.pdf"));
			doc.open();
			
			BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); //创建文字字体
			BaseFont bfc = BaseFont.createFont("D:/ht.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //创建中文的文字字体,自定义字体文件
			PdfContentByte cb = writer.getDirectContent();
			
			cb.saveState();
			cb.beginText();
			cb.moveText(20, 300); //设置文字的位置
			cb.setFontAndSize(bf, 12); //设置文字的大小
			cb.setColorFill(BaseColor.RED); //设置文字颜色
			cb.showText("this is an English test."); //设置文字内容
			cb.endText();
			cb.restoreState();

			cb.saveState();
			cb.beginText();
			cb.moveText(20, 280);
			cb.setFontAndSize(bfc, 12);
			cb.showText("这是一个中文测试。It can also English."); //中文文字的测试
			cb.endText();
			cb.restoreState();

		} catch (DocumentException | IOException e) {
			e.printStackTrace();
		} finally {
			doc.close();
		}
	}
}

以上

java itext添加图片生成pdf示例

java itext生成pdf添加图片
下面是示例代码

import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;


public class Test {
	public static void main(String[] args) {
		Rectangle pSize = new Rectangle(4620, 3572);
		Document doc = new Document(pSize); //创建文档

		try {
			PdfWriter.getInstance(doc, new FileOutputStream("testpdf.pdf"));
			doc.open();
			
			Image bgImage = Image.getInstance("bg.png"); //创建图片
			bgImage.setAlignment(Image.UNDERLYING); //设置为背景图
			bgImage.scaleAbsolute(4620, 3572); //设置图片大小,这里是作背景,跟文档一样大
			bgImage.setAbsolutePosition(0, 0); //设置图片位置,x,y的0,0坐标为文档左下角
			doc.add(bgImage); //加入图片

			Image img = Image.getInstance("1.png"); //创建图片
			img.scaleAbsolute((float)164.409, (float)267.457); //设置图片大小
			img.setRotationDegrees(0); //设置图片角度,可旋转图片
			img.setAbsolutePosition(100, 1000); //设置图片位置,x,y为图片左下角到文档左下角的距离
			doc.add(img);

		} catch (DocumentException | IOException e) {
			e.printStackTrace();
		} finally {
			doc.close();
		}
	}
}

以上

java 文本生成图片示例

用java将文字输出为图片示例

import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.font.TextAttribute;
import java.util.HashMap;
import javax.imageio.*;

public class txt2img {

    public static void main(String[] args) throws Exception {
        String text        = args[0];
        String family      = args[1];
        String size        = args[2];
        String bold        = args[3];
        String italic      = args[4];
        String underline   = args[5];
        String fcolor      = args[6];
        String bcolor      = args[7];
        String filename    = args[8];

        HashMap<TextAttribute, Object> hm = new HashMap<TextAttribute, Object>();
        
        // 定义字体
        if (family.trim().equals("") || family == null || family == "default") {
            hm.put(TextAttribute.FAMILY, "Simsun");
        } else {
            hm.put(TextAttribute.FAMILY, family);
        }
        // 定义字号
        if (size.trim().equals("") || size == null) {
            hm.put(TextAttribute.SIZE, 18);
        } else {
            hm.put(TextAttribute.SIZE, Integer.parseInt(size));
        }
        // System.out.println("size: " + size);
        // 定义是否粗体
        if (bold.trim().equals("1")) {
            // System.out.println("bold");
            hm.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
        }
        // 定义是否斜体
        if (italic.trim().equals("1")) {
            // System.out.println("italic");
            hm.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
        }
        // 定义是否有下划线
        if (underline.trim().equals("1")) {
            // System.out.println("underline");
            hm.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        }
        // 设置字体颜色
        if (fcolor.indexOf(",") == -1 || fcolor == null) {
            hm.put(TextAttribute.FOREGROUND, new Color(0, 0, 0));
        } else {
            String[] fc = fcolor.split(",");
            hm.put(TextAttribute.FOREGROUND, new Color(Integer.parseInt(fc[0]), Integer.parseInt(fc[1]), Integer.parseInt(fc[2])));
        }
        // 设置背景颜色
        if (bcolor.indexOf(",") > -1 && bcolor != null) {
            String[] bc = bcolor.split(",");
            hm.put(TextAttribute.BACKGROUND, new Color(Integer.parseInt(bc[0]), Integer.parseInt(bc[1]), Integer.parseInt(bc[2])));
        }
        
        Font font = new Font(hm);
        createImage(text, font, new File(filename));
    }

    // 根据str,font的样式以及输出文件目录
    public static void createImage(String str, Font font, File outFile) throws Exception{
        // 获取font的样式应用在str上的整个矩形
        Rectangle2D r = font.getStringBounds(str, new FontRenderContext(AffineTransform.getScaleInstance(1, 1), false, false));
        int unitHeight = (int)Math.floor(r.getHeight()) + 1; // 获取单个字符的高度
        // 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
        int width = (int)Math.round(r.getWidth()) + 1;
        int height = unitHeight + 3; // 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
        // 创建图片
        BufferedImage imageb = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g = imageb.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // 反锯齿
        g.setFont(font); // 设置画笔字体
        g.drawString(str, 0, font.getSize()); // 画出字符串
        g.dispose();

        ImageIO.write(imageb, "png", outFile); // 输出png图片
    }
}

java对象与json相互转换示例

java 对象与json互转,用到了谷歌(Google)的Gson类库。

import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

class JsonOpen {
	private List<Zone> zones;
	public List<Zone> getZones() {
		return zones;
	}
	public void setZones(List<Zone> zones) {
		this.zones = zones;
	}
}

class Zone {
	private List<CardObject> cards;
	public List<CardObject> getCards() {
		return cards;
	}
	public void setCards(List<CardObject> cards) {
		this.cards = cards;
	}
}

class CardObject {
	private String zone;
	private String line;
	private String row;
	private String batch;
	private String number;
	private String path;
	public String getZone() {
		return zone;
	}
	public void setZone(String zone) {
		this.zone = zone;
	}
	public String getLine() {
		return line;
	}
	public void setLine(String line) {
		this.line = line;
	}
	public String getRow() {
		return row;
	}
	public void setRow(String row) {
		this.row = row;
	}
	public String getBatch() {
		return batch;
	}
	public void setBatch(String batch) {
		this.batch = batch;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
}

/**
 * 测试java对象和json转换
 *
 * @author lxl
 * @version 1.0
 * @created 2015-08-20 16:54:26
 * @history 
 * @see
 */
public class Test {
	public static void main(String[] args) {
		// toJson();
		toObject();
	}
	
	public static void toJson(){
		List<CardObject> cards = new ArrayList<CardObject>();
		CardObject card = new CardObject();
		card.setZone("A");
		card.setLine("A");
		card.setRow("1");
		card.setBatch("15315AA020");
		card.setNumber("008100000803");
		card.setPath("");
		cards.add(card);
		CardObject card2 = new CardObject();
		card2.setZone("A");
		card2.setLine("B");
		card2.setRow("1");
		card2.setBatch("15315AA020");
		card2.setNumber("008100000803");
		card2.setPath("");
		cards.add(card2);
		CardObject card3 = new CardObject();
		card3.setZone("A");
		card3.setLine("C");
		card3.setRow("1");
		card3.setBatch("15315AA020");
		card3.setNumber("008100000803");
		card3.setPath("");
		cards.add(card3);

		Zone zone = new Zone();
		zone.setCards(cards);

		List<Zone> zones = new ArrayList<Zone>();
		zones.add(zone);

		JsonOpen jo = new JsonOpen();
		jo.setZones(zones);

		Gson gson = new GsonBuilder().create();
		String result = gson.toJson(jo);
		System.out.println(result);
	}
	
	public static void toObject(){
		String json = "{'zones':[{'cards':[{'zone':'A','line':'A','row':'1','batch':'15315AA020','number':'008100000803','path':''}," +
		"{'zone':'A','line':'B','row':'1','batch':'15315AA020','number':'008100000803','path':''}," +
		"{'zone':'A','line':'C','row':'1','batch':'15315AA020','number':'008100000803','path':''}," +
		"{'zone':'A','line':'D','row':'1','batch':'15315AA020','number':'008100000803','path':''}," +
		"{'zone':'A','line':'E','row':'1','batch':'15315AA020','number':'008100000803','path':''}]}]}";

		Gson gson = new Gson();
		JsonOpen jo = gson.fromJson(json, JsonOpen.class);
		System.out.println(jo.getZones().size());
		System.out.println(jo.getZones().get(0).getCards().size());

		for (int i = 0; i < jo.getZones().size(); i++) {
			List<CardObject> cards = jo.getZones().get(i).getCards();
			for (int j = 0; j < cards.size(); j++) {
				System.out.println("zone:" + cards.get(j).getZone());
				System.out.println("line:" + cards.get(j).getLine());
				System.out.println("row:" + cards.get(j).getRow());
				System.out.println("batch:" + cards.get(j).getBatch());
				System.out.println("number:" + cards.get(j).getNumber());
				System.out.println("path:" + cards.get(j).getPath());
			}
		}
 	}
}