package?common;
創(chuàng)新互聯(lián)服務項目包括赤城網(wǎng)站建設、赤城網(wǎng)站制作、赤城網(wǎng)頁制作以及赤城網(wǎng)絡營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關系等,向廣大中小型企業(yè)、政府機構等提供互聯(lián)網(wǎng)行業(yè)的解決方案,赤城網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務的客戶以成都為中心已經(jīng)輻射到赤城省份的部分城市,未來相信會繼續(xù)擴大服務區(qū)域并繼續(xù)獲得客戶的支持與信任!
import?java.awt.Color;
import?java.awt.Graphics2D;
import?java.awt.Image;
import?java.awt.image.BufferedImage;
import?java.io.File;
import?java.io.IOException;
import?java.util.HashMap;
import?java.util.Map;
import?javax.imageio.ImageIO;
import?jp.sourceforge.qrcode.QRCodeDecoder;
import?jp.sourceforge.qrcode.exception.DecodingFailedException;
import?com.google.zxing.BarcodeFormat;
import?com.google.zxing.Binarizer;
import?com.google.zxing.BinaryBitmap;
import?com.google.zxing.EncodeHintType;
import?com.google.zxing.LuminanceSource;
import?com.google.zxing.MultiFormatReader;
import?com.google.zxing.MultiFormatWriter;
import?com.google.zxing.NotFoundException;
import?com.google.zxing.WriterException;
import?com.google.zxing.common.BitMatrix;
import?com.google.zxing.common.HybridBinarizer;
import?com.swetake.util.Qrcode;
/**
*?二維碼生成工具類
*?@author?Cloud
*?@data???2016-12-15
*?QRCode
*/
public?class?QRCodeUtil?{
//二維碼顏色
private?static?final?int?BLACK?=?0xFF000000;
//二維碼顏色
private?static?final?int?WHITE?=?0xFFFFFFFF;
/**
*?span?style="font-size:18px;font-weight:blod;"ZXing?方式生成二維碼/span
*?@param?text????a?href="javascript:void();"二維碼內容/a
*?@param?width????二維碼寬
*?@param?height????二維碼高
*?@param?outPutPath????二維碼生成保存路徑
*?@param?imageType????????二維碼生成格式
*/
public?static?void?zxingCodeCreate(String?text,?int?width,?int?height,?String?outPutPath,?String?imageType){
MapEncodeHintType,?String?his?=?new?HashMapEncodeHintType,?String();
//設置編碼字符集
his.put(EncodeHintType.CHARACTER_SET,?"utf-8");
try?{
//1、生成二維碼
BitMatrix?encode?=?new?MultiFormatWriter().encode(text,?BarcodeFormat.QR_CODE,?width,?height,?his);
//2、獲取二維碼寬高
int?codeWidth?=?encode.getWidth();
int?codeHeight?=?encode.getHeight();
//3、將二維碼放入緩沖流
BufferedImage?image?=?new?BufferedImage(codeWidth,?codeHeight,?BufferedImage.TYPE_INT_RGB);
for?(int?i?=?0;?i??codeWidth;?i++)?{
for?(int?j?=?0;?j??codeHeight;?j++)?{
//4、循環(huán)將二維碼內容定入圖片
image.setRGB(i,?j,?encode.get(i,?j)???BLACK?:?WHITE);
}
}
File?outPutImage?=?new?File(outPutPath);
//如果圖片不存在創(chuàng)建圖片
if(!outPutImage.exists())
outPutImage.createNewFile();
//5、將二維碼寫入圖片
ImageIO.write(image,?imageType,?outPutImage);
}?catch?(WriterException?e)?{
e.printStackTrace();
System.out.println("二維碼生成失敗");
}?catch?(IOException?e)?{
e.printStackTrace();
System.out.println("生成二維碼圖片失敗");
}
}
/**
*?span?style="font-size:18px;font-weight:blod;"二維碼解析/span
*?@param?analyzePath????二維碼路徑
*?@return
*?@throws?IOException
*/
@SuppressWarnings({?"rawtypes",?"unchecked"?})
public?static?Object?zxingCodeAnalyze(String?analyzePath)?throws?Exception{
MultiFormatReader?formatReader?=?new?MultiFormatReader();
Object?result?=?null;
try?{
File?file?=?new?File(analyzePath);
if?(!file.exists())
{
return?"二維碼不存在";
}
BufferedImage?image?=?ImageIO.read(file);
LuminanceSource?source?=?new?LuminanceSourceUtil(image);
Binarizer?binarizer?=?new?HybridBinarizer(source);??
BinaryBitmap?binaryBitmap?=?new?BinaryBitmap(binarizer);
Map?hints?=?new?HashMap();
hints.put(EncodeHintType.CHARACTER_SET,?"UTF-8");
result?=?formatReader.decode(binaryBitmap,?hints);
}?catch?(NotFoundException?e)?{
e.printStackTrace();
}??
return?result;
}
/**
*?span?style="font-size:18px;font-weight:blod;"QRCode?方式生成二維碼/span
*?@param?content????二維碼內容
*?@param?imgPath????二維碼生成路徑
*?@param?version????二維碼版本
*?@param?isFlag????是否生成Logo圖片????為NULL不生成
*/
public?static?void?QRCodeCreate(String?content,?String?imgPath,?int?version,?String?logoPath){
try?{??
Qrcode?qrcodeHandler?=?new?Qrcode();??
//設置二維碼排錯率,可選L(7%)?M(15%)?Q(25%)?H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小????
qrcodeHandler.setQrcodeErrorCorrect('M');??
//N代表數(shù)字,A代表字符a-Z,B代表其他字符??
qrcodeHandler.setQrcodeEncodeMode('B');??
//版本1為21*21矩陣,版本每增1,二維碼的兩個邊長都增4;所以版本7為45*45的矩陣;最高版本為是40,是177*177的矩陣??
qrcodeHandler.setQrcodeVersion(version);
//根據(jù)版本計算尺寸
int?imgSize?=?67?+?12?*?(version?-?1)?;??
byte[]?contentBytes?=?content.getBytes("gb2312");??
BufferedImage?bufImg?=?new?BufferedImage(imgSize?,?imgSize?,BufferedImage.TYPE_INT_RGB);??
Graphics2D?gs?=?bufImg.createGraphics();??
gs.setBackground(Color.WHITE);??
gs.clearRect(0,?0,?imgSize?,?imgSize);??
//?設定圖像顏色??BLACK
gs.setColor(Color.BLACK);
//?設置偏移量?不設置可能導致解析出錯??
int?pixoff?=?2;
//?輸出內容??二維碼??
if?(contentBytes.length??0??contentBytes.length??130)?{
boolean[][]?codeOut?=?qrcodeHandler.calQrcode(contentBytes);
for?(int?i?=?0;?i??codeOut.length;?i++)?{
for?(int?j?=?0;?j??codeOut.length;?j++)?{
if?(codeOut[j][i])?{??
gs.fillRect(j?*?3?+?pixoff,?i?*?3?+?pixoff,?3,?3);
}??
}??
}??
}?else?{??
System.err.println("QRCode?content?bytes?length?=?"?+?contentBytes.length?+?"?not?in?[?0,130?].?");??
}
/*?判斷是否需要添加logo圖片?*/
if(logoPath?!=?null){
File?icon?=?new?File(logoPath);
if(icon.exists()){
int?width_4?=?imgSize?/?4;
int?width_8?=?width_4?/?2;
int?height_4?=?imgSize?/?4;
int?height_8?=?height_4?/?2;
Image?img?=?ImageIO.read(icon);
gs.drawImage(img,?width_4?+?width_8,?height_4?+?height_8,width_4,height_4,?null);
gs.dispose();
bufImg.flush();
}else{
System.out.println("Error:?login圖片還在在!");
}
}
gs.dispose();
bufImg.flush();
//創(chuàng)建二維碼文件
File?imgFile?=?new?File(imgPath);
if(!imgFile.exists())
imgFile.createNewFile();
//根據(jù)生成圖片獲取圖片
String?imgType?=?imgPath.substring(imgPath.lastIndexOf(".")?+?1,?imgPath.length());
//?生成二維碼QRCode圖片??
ImageIO.write(bufImg,?imgType,?imgFile);??
}?catch?(Exception?e)?{??
e.printStackTrace();??
}
}
/**
*?span?style="font-size:18px;font-weight:blod;"QRCode二維碼解析/span
*?@param?codePath????二維碼路徑
*?@return????解析結果
*/
public?static?String?QRCodeAnalyze(String?codePath)?{
File?imageFile?=?new?File(codePath);
BufferedImage?bufImg?=?null;??
String?decodedData?=?null;??
try?{
if(!imageFile.exists())
return?"二維碼不存在";
bufImg?=?ImageIO.read(imageFile);
QRCodeDecoder?decoder?=?new?QRCodeDecoder();??
decodedData?=?new?String(decoder.decode(new?ImageUtil(bufImg)),?"gb2312");??
}?catch?(IOException?e)?{??
System.out.println("Error:?"?+?e.getMessage());??
e.printStackTrace();??
}?catch?(DecodingFailedException?dfe)?{??
System.out.println("Error:?"?+?dfe.getMessage());??
dfe.printStackTrace();??
}
return?decodedData;
}
}
3、最后貼測試代碼:
package?test;
import?java.awt.image.BufferedImage;
import?java.io.InputStream;
import?java.net.URL;
import?javax.imageio.ImageIO;
import?common.ImageUtil;
import?common.QRCodeUtil;
import?jp.sourceforge.qrcode.QRCodeDecoder;
/**
*?二維碼生成測試類
*?@author?Cloud
*?@data???2016-11-21
*?QRCodeTest
*/
public?class?QRCodeTest?{
public?static?void?main(String[]?args)?throws?Exception?{
/**
*????QRcode?二維碼生成測試
*????QRCodeUtil.QRCodeCreate("",?"E://qrcode.jpg",?15,?"E://icon.png");
*/
/**
*?????QRcode?二維碼解析測試
*????String?qrcodeAnalyze?=?QRCodeUtil.QRCodeAnalyze("E://qrcode.jpg");
*/
/**
*?ZXingCode?二維碼生成測試
*?QRCodeUtil.zxingCodeCreate("",?300,?300,?"E://zxingcode.jpg",?"jpg");
*/
/**
*?ZxingCode?二維碼解析
*????String?zxingAnalyze?=??QRCodeUtil.zxingCodeAnalyze("E://zxingcode.jpg").toString();
*/
System.out.println("success");
}
}
可以參考下.自己寫的一個例子
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.Queue;
import com.google.zxing.WriterException;
public class QrPrint implements Printable {
public void print() throws PrinterException {
PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.defaultPage();
Paper paper = new Paper();
double margin = 0.1; // half inch
paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2,paper.getHeight() - margin * 2);
pf.setPaper(paper);
pj.setPrintable(this, pf);
pj.print();
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if ("判斷如果打印完了就退出") {
return Printable.NO_SUCH_PAGE;
}
try {
Image eanImage = generateEANBufferedImage(content,120,20);
Graphics2D g2 = (Graphics2D) graphics;
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); //設置可成像的X和Y軸的距離
g2.drawImage(eanImage, 0, 80, null); //設置打印的邊距
g2.drawString("字符串:",130,20);
} catch (WriterException e) {
e.printStackTrace();
return Printable.NO_SUCH_PAGE;
}
return Printable.PAGE_EXISTS;
}
private BufferedImage generateBufferedImage(String content,int width,int height) throws WriterException {
HashtableEncodeHintType,String hints = new HashtableEncodeHintType,String();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.EAN_13, width, height, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
}
你可以自行google或baidu查一下相關關鍵字:jasperreport applet ,jasperreport barcode之類的,提供的框架http //git oschina net/xautlx/s2jh里面提供一個基礎的原型實供現(xiàn)參考。
引用spire.barcode.jar包
//創(chuàng)建BarcodeSettings對象
BarcodeSettings?settings?=?new?BarcodeSettings();
//設置條碼類型為
QR二維碼settings.setType(BarCodeType.QR_Code);???????
//設置二維碼數(shù)據(jù)
settings.setData("Hello?123456789");
//設置二維碼顯示數(shù)據(jù)
settings.setData2D("Hello?123456789");?????
//設置數(shù)據(jù)類型
settings.setQRCodeDataMode(QRCodeDataMode.Alpha_Number);
//設置二維碼模型寬度
settings.setX(1.0f);
//設置二維碼糾錯級別settings.setQRCodeECL(QRCodeECL.H);
//創(chuàng)建BarCodeGenerator實例
BarCodeGenerator?barCodeGenerator?=?new?BarCodeGenerator(settings);
//根據(jù)settings生成圖像數(shù)據(jù),保存至BufferedImage
BufferedImage?bufferedImage?=?barCodeGenerator.generateImage();
//將圖片數(shù)據(jù)保存為PNG格式
ImageIO.write(bufferedImage,?"png",?new?File("QRCode.png"));
Print.java--打印內容定義 [code] import java.awt.*; import java.awt.event.*; import java.awt.print.*; import java.awt.image.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.event.*; import java.util.*; import java.io.*; public class Print implements Printable{ int m_wPage; int m_hPage; int m_orientation; Printable m_target; int maxNumPage=1; String title="數(shù)據(jù)表格打印"; Font titleFont=new Font("黑體",Font.BOLD,14); boolean hasTail=true; int tailAlign=0; int headAlign=0; int topSpace=0; int leftSpace=0; int yStart=0; int yEnd=0; int xStart=topSpace; int xEnd=0; int x=0,y=0; String strTemp="打印內容"; public void doPrint(){ try{ m_orientation=PageFormat.PORTRAIT; //設置打印對象,默認紙張 PrinterJob prnJob=PrinterJob.getPrinterJob(); PageFormat pageFormat=prnJob.defaultPage(); pageFormat.setOrientation(m_orientation); m_wPage=(int)(pageFormat.getWidth()); m_hPage=(int)(pageFormat.getHeight()); //將待打印的窗體根據(jù)默認紙張設置傳入打印對象 prnJob.setPrintable(this,pageFormat); if(!prnJob.printDialog()) return; prnJob.print(); }catch(PrinterException ex){ ex.printStackTrace(); System.err.println("打印錯誤:"+ex.toString()); } } /** * 初始化打印參數(shù) */ public void initPrintParameter() { } /** *構造打印內容,以送打印機打印 */ public int print(Graphics pg,PageFormat pageFormat, int pageIndex) throws PrinterException{ //初始化打印參數(shù) initPrintParameter(); //將畫布設置為頁面大小 pg.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY()); int wPage=0; int hPage=0; //根據(jù)打印機頁面設置調整畫布大小 if(pageFormat.getOrientation()==pageFormat.PORTRAIT){ wPage=(int)pageFormat.getImageableWidth(); hPage=(int)pageFormat.getImageableHeight(); } else{ wPage=(int)pageFormat.getImageableWidth(); wPage+=wPage/2; hPage=(int)pageFormat.getImageableHeight(); pg.setClip(0,0,wPage,hPage); } wPage=wPage-2*leftSpace; hPage=hPage-2*topSpace; xStart=leftSpace; xEnd=wPage-2; //為畫布設置顏色和字體 int y=topSpace; pg.setFont(titleFont); pg.setColor(Color.black); //畫標題,并使其居中 Font fn=pg.getFont(); FontMetrics fm=pg.getFontMetrics(); y+=fm.getAscent(); alignText(title,pg,y,xStart,xEnd,headAlign); y+=30; x=leftSpace+2; Font headerFont=new Font("宋體",Font.BOLD,14); pg.setFont(headerFont); fm=pg.getFontMetrics(); int h=fm.getAscent(); yStart=y-1; y+=h; pg.setFont(headerFont); fm=pg.getFontMetrics(); int header=y; h=fm.getHeight(); //計算行高,每頁行數(shù),總行數(shù)和指定頁碼的起始行、結束行 int rowH=Math.max(h,10); int tailH=rowH+30; int rowPerPage=0; int leftPix=0; if(hasTail){ rowPerPage=(hPage-header-tailH)/rowH; leftPix=(hPage-header-tailH)%rowH; yEnd=hPage-leftPix-tailH+2; } else{ rowPerPage=(hPage-header)/rowH; leftPix=(hPage-header)%rowH; yEnd=hPage-leftPix+2; } pg.drawString(strTemp,x,y); //畫表格邊框 pg.drawLine(xStart,yStart,xStart,yEnd); pg.drawLine(xStart,yStart,xEnd,yStart); pg.drawLine(xEnd,yStart,xEnd,yEnd); pg.drawLine(xStart,yEnd,xEnd,yEnd); //打印頁碼 if(hasTail){ int pageNumber=pageIndex+1; String s="第"+pageNumber+"頁"; alignText(s,pg,yEnd+30,xStart,xEnd,tailAlign); } System.gc(); return PAGE_EXISTS; } /** * 文字排列,坐標在y處,顯示范圍(start-end) * 0表示居中顯示,1表示左對齊,2表示右對齊 */ private void alignText(String s,Graphics pg,int y,int start, int end,int mode){ Font fn=pg.getFont(); FontMetrics fm=pg.getFontMetrics(); int wString=fm.stringWidth(s); int x=start; switch(mode) { case 0: if((end-start-wString)0) x=start+(end-start-wString)/2; break; case 1: break; case 2: if((end-start-wString)0) x=start+(end-start-wString); break; } pg.drawString(s,x,y); } public static void main(String[] args){ Print p=new Print(); p.doPrint(); } } [code] 運行方法: javac -d . Print.java java Print 自己運行一下 from:
采納哦
如一樓所說,你的jsp源文件的java代碼是在服務器上執(zhí)行的,客戶端接收到的只有html
用JavaScript打印吧
input
id="btnPrint"
type="button"
value="打印"
onclick="javascript:window.print();"
/
可以用樣式控制,你想讓那塊打印就打印啊,樣式如下:
style
type="text/css"
media=print
.noprint{display
:
none
}
/style
然后使用樣式就可以:
p
class="noprint"不需要打印的地方/p