Java Export PDF file

Source: Internet
Author: User

1, use the package as follows:

Itext-2.1.7.jar

Itextasian-1.5.2.jar

Download add: Click to download Jar package

2, the code is as follows:

Package com.junlenet.action;
Import Java.awt.Color;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletOutputStream;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import com.lowagie.text.Document;
Import com.lowagie.text.Element;
Import Com.lowagie.text.Font;
Import Com.lowagie.text.HeaderFooter;
Import Com.lowagie.text.Image;
Import com.lowagie.text.PageSize;
Import Com.lowagie.text.Paragraph;
Import Com.lowagie.text.Phrase;
Import Com.lowagie.text.pdf.BaseFont;
Import Com.lowagie.text.pdf.PdfPCell;
Import com.lowagie.text.pdf.PdfPTable;

Import Com.lowagie.text.pdf.PdfWriter; /** * Servlet Implementation class Pdfaction/@WebServlet (description = "Pdfaction", Urlpatterns= {"/pdfaction"}) public class Pdfaction extends HttpServlet {private static final long serialversionuid = 1L;
        /** * @see httpservlet#httpservlet () * * * Public pdfaction () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, HTTPSERVLETRESP Onse response) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexceptio
	N, IOException {doPost (request, response); /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) * * protected void DoPost ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {try {basefont Bfchi   
		    Nese = Basefont.createfont ("Stsong-light", "unigb-ucs2-h", basefont.not_embedded);
		    Font fontChinese10 = new Font (Bfchinese, font.normal);
		    Font fontChinese12 = new Font (Bfchinese, font.normal); Font Fontchinese= new Font (Bfchinese, font.normal);
			Paragraph emptyLine5 = new Paragraph (5, "");
			
		    Paragraph emptyLine10 = new Paragraph (10, "");
			Document document = new document (pagesize.a4,40,40,30,30);
			Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
			PDFWriter writer = pdfwriter.getinstance (document, New FileOutputStream (filepathstring));
			PDFWriter writer = pdfwriter.getinstance (document, BAOs);
			Setting the footer needs to be document.setfooter before open (Createfooter (FONTCHINESE10));
			Document.setheader (CreateHeader (FONTCHINESE10));
			Document.open ();
			Document.add (New Paragraph ("June le Net", fontChinese14));
			Document.add (Createimg ());
			Document.newpage ();
			Document.add (New Paragraph ("June le Net", fontChinese14));
			Document.add (EMPTYLINE10);
			Document.add (Createtab (fontChinese12));
			Document.newpage ();
			Document.add (New Paragraph ("June le Net", fontChinese14));
			Document.newpage ();
            Document.close (); Response.setheader ("Content-disposition", "attachment; filename=\ "" +new String ("PDF file". GetBytes (), "iso8859-1") + ". pdf\");  
            Response.setcontentlength (Baos.size ());
            Servletoutputstream outputstream = Response.getoutputstream ();  
            Baos.writeto (OutputStream);  
            Outputstream.flush ();  
		Outputstream.close ();
		catch (Exception e) {e.printstacktrace (); } private pdfptable Createtab (Font fontChinese12) {try {pdfptable tab = new Pdfptable (5);//How many columns Tab.settotal Width (515); Fixed width tab.setlockedwidth (true); Width tab.setwidths (new int[]{103,103,103,103,103}) must be locked when using a fixed width;
			The width of each column is only valid for the fixed width, and if the table uses percentages to set the total width, then here is the percent of usage. Tab.setwidthpercentage (Percen); The table width is set to 100%//tab.getdefaultcell (). SetBorder (0);
			The Uniform setting border is 0, but it is not valid if cells are added separately.
			Pdfpcell cell_id = new Pdfpcell (New Paragraph ("ordinal", fontChinese12));
			Cell_id.setfixedheight (20),//Cell height//cell_id.setpaddingleft (0); Cell_id.setcolspan (2); Merge column//cell_id.setrowspan (2);  Combined row//cell_id.setborder (0); //Border//cell_id.addelement (tab);
			
			Table nested cells can be added to a table Tab.addcell (cell_id);
			Pdfpcell cell_name = new Pdfpcell (new Paragraph ("name", FontChinese12));
			
			Tab.addcell (Cell_name);
			Pdfpcell cell_age = new Pdfpcell (New Paragraph ("Age", fontChinese12));
			
			Tab.addcell (Cell_age);
			Pdfpcell cell_email = new Pdfpcell (New Paragraph ("Mailbox", FontChinese12));
			
			Tab.addcell (Cell_email);
			Pdfpcell Cell_isok = new Pdfpcell (new Paragraph ("qualified", FontChinese12));
			
			Tab.addcell (Cell_isok);
			list<map<string, string>> data = Tabdata ();
			Pdfpcell cell_temp = null;
				For (map<string, string> map:data) {cell_temp = new Pdfpcell (Paragraph ("id"), map.get);
				Tab.addcell (cell_temp);
				Cell_temp = new Pdfpcell (New Paragraph (Map.get ("name"), FontChinese12));
				Tab.addcell (cell_temp);
				Cell_temp = new Pdfpcell (New Paragraph (Map.get ("Age"), fontChinese12));
				Tab.addcell (cell_temp); Cell_temp = new Pdfpcell (New ParagrapH (map.get ("email"), fontChinese12);
				Tab.addcell (cell_temp);
				Cell_temp = new Pdfpcell (New Paragraph (Map.get ("isOK"), fontChinese12));
			Tab.addcell (cell_temp);
		} return tab;
			catch (Exception e) {e.printstacktrace ();
		return null; } private List<map<string, string>> Tabdata () {list<map<string, string>> data = new ArrayL
		Ist<map<string,string>> ();
		map<string, string> item = NULL;
			for (int i = 0; i < i++) {item = new hashmap<string, string> ();
			Item.put ("id", "1000" +i);
			Item.put ("name", "Hwj_" +i);
			Item.put ("Age", "" + (20+i));
			Item.put ("email", "2368890" +i+ "79qq.com"); Item.put ("isOK", i%2==0?)
			Qualified ":" unqualified ");
		Data.add (item);
	} return data;
			Private Image createimg () {try {String url = ' http://junlenet.com/uploads/allimg/160424/1-160424122217.jpg ';
			Image image = Image.getinstance (URL);
			Image.scaletofit (200,120);
		return image; catch (Exception e) {REturn null; } private HeaderFooter Createfooter (Font fontChinese10) {String footStr1 = \t\t June le network \ t www.j UNL enet.com\t\t\t\t\
		 T\t\t\t\t\t\t\t\t\t ";  
         HeaderFooter footer=new HeaderFooter (New Phrase (FOOTSTR1,FONTCHINESE10), New Phrase ("/3\t\t", FontChinese10));  
         Footer.setalignment (Element.align_right);
         Footer.setbordercolortop (New Color (0,0,0));
         Footer.setborderwidthtop (1);
         Footer.setborderwidthbottom (0);
         Footer.setborderwidthleft (0);
         Footer.setborderwidthright (0);
	return footer;
Private HeaderFooter CreateHeader (Font fontChinese10) {String footStr1 = "www.j unl enet.com\t\tqq:962884205";
		HeaderFooter footer=new HeaderFooter (New Phrase (FOOTSTR1,FONTCHINESE10), New Phrase ("/3\t\t", FontChinese10));
        HeaderFooter footer=new HeaderFooter (New Phrase (FOOTSTR1,FONTCHINESE10), false);  
        Footer.setalignment (Element.align_left);
        Footer.setborderwidthtop (0); Footer.setbordercolorbOttom (New Color (0,0,0));
        Footer.setborderwidthbottom (1);
        Footer.setborderwidthleft (0);
        Footer.setborderwidthright (0);
	return footer;
 }
	

}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.