Title java uses itextPDF to generate PDF files, save them locally and upload them to the ftp server
Required jars:itext-asian-5.2.0.jar,itextpdf-5.5.5.jar,commons-net-3.3.jar This is the only way to do it because it cannot be uploaded.
Set attributes on the page, such as headers and footers
package com.ibm.business.util;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
/import com.sign.system.PathCons;
import com.sign.util.PathUtil;
/
/
- Set additional page properties
*/
public class PDFBuilder extends PdfPageEventHelper {
/** * Header */ public String header = ""; /** * Document font size, footer and header should be consistent with the text size */ public int presentFontSize = 12; /** * Document page size, it is best to pass it in before, otherwise it will default to A4 paper */ public Rectangle pageSize = PageSize.A4; // template public PdfTemplate total; //Basic font object public BaseFont bf = null; // Font object generated using basic fonts, generally used to generate Chinese text public Font fontDetail = null; public PDFBuilder() { } /** * * Creates a new instance of PdfReportM1HeaderFooter constructor. * * @param yeMei * Header string * @param presentFontSize *Data body font size * @param pageSize * Page document size, A4, A5, A6 horizontal flip and other Rectangle objects */ public PDFBuilder( int presentFontSize, Rectangle pageSize) { this.presentFontSize = presentFontSize; this.pageSize = pageSize; } public void setHeader(String header) { this.header = header; } public void setPresentFontSize(int presentFontSize) { this.presentFontSize = presentFontSize; } /** * * Create template when TODO document is opened * * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.text.Document) */ public void onOpenDocument(PdfWriter writer, Document document) { total = writer.getDirectContent().createTemplate(50, 50);//The length, width and height of the rectangle totaling pages } /** * * TODO When closing each page, write the header and the words 'what page is total'. * * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { this.addPage(writer, document); // this.addWatermark(writer); } //Add paging public void addPage(PdfWriter writer, Document document){ try { if (bf == null) { bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false); } if (fontDetail == null) { fontDetail = new Font(bf, presentFontSize, Font.NORMAL);//data body font } } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 2. Write the first half of page X/total int pageS = writer.getPageNumber(); String foot1 = "No. " + pageS + " Page /Total"; Phrase footer = new Phrase(foot1, fontDetail); // 3. Calculate the length of foot1 in the first half, and then locate the x-axis coordinates of the two words 'Y page' in the last part. The font length must also be calculated = len float len = bf.getWidthPoint(foot1, presentFontSize); // 4. Get the current PdfContentByte PdfContentByte cb = writer.getDirectContent(); // 5. Write footer 1, the x-axis is (right margin + left margin + right() -left()- len)/2.0F //An additional offset of 20F is suitable for human visual perception, otherwise it will look too left to the naked eye. //, the y-axis is the bottom boundary -20, otherwise the edge will overlap into the data body and it will not be the footer; note that the Y-axis is accumulated from bottom to top, and the Top value at the top is hundreds of miles larger than Bottom. of. ColumnText .showTextAligned( cb, Element.ALIGN_CENTER, footer, (document.rightMargin() + document.right() + document.leftMargin() - document.left() - len) / 2.0F + 20F, document.bottom() - 20, 0); // 6. Write the template of footer 2 (that is, the two words "Y page" in the footer) to the document, calculate the sum of the Y axis of the template, X = (right border - left border - len value of the first half)/ 2.0F+ // len, the y axis remains the same as before, the bottom boundary is -20 cb.addTemplate(total, (document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20F, document.bottom() - 20); //Adjust the position of template display } /** * * TODO When closing the document, replace the template and complete the entire header and footer components. * * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.text.Document) */ public void onCloseDocument(PdfWriter writer, Document document) { // 7. The last step is to replace the template with the actual Y value when closing the document. At this point, page x of y is completed and is perfectly compatible with various document sizes. total.beginText(); total.setFontAndSize(bf, presentFontSize);//The font and color of the generated template String foot2 = " " + (writer.getPageNumber()-1) + " page"; total.showText(foot2);//The content displayed by the template total.endText(); total.closePath(); }
}
2. How to generate PDF
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import com.ibm.business.util.PDFBuilder;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class pdf {
private static FTPClient ftp = new FTPClient();
/**
* Generate PDF content
*/
public static ByteArrayOutputStream T_LOG_RECORD_PREPAIDPDF(String burks,String gonssi,String date){ Document document = new Document(); Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth()); pageSize.rotate(); document.setPageSize(pageSize);//Set the document paper size PdfWriter writer=null; ByteArrayOutputStream os = new ByteArrayOutputStream(); try { BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//Set the font Font titlefont = new Font(bfChinese,14,Font.BOLD);//Font style Font companyfont = new Font(bfChinese,10,Font.NORMAL);//Font style Font rowfont = new Font(bfChinese,10,Font.NORMAL);//Font style PDFBuilder pdfBuilder = new PDFBuilder(); writer = PdfWriter.getInstance(document,os); writer.setPageEvent(pdfBuilder); document.open(); Double TAX_FREE_AMT=0.0; Double AMORTIZE_MONTH_ACCOUNT=0.0; Double CURRENT_MONTH_ACCOUNT=0.0; Double TOTAL_AMORTIZE_ACCOUNT=0.0; Double AMORTIZE_BALANCE=0.0; \t\t PdfPTable pdfPTable2 = new PdfPTable(13); float[] columnWidth={55,50,50,110,50,50,50,85,50,50,60,80,80}; pdfPTable2.setTotalWidth(columnWidth); pdfPTable2.setLockedWidth(true); \t\t\t\t document.newPage(); //Header information document.add( pdfPTable2.addCell(createCell("Expense Details", 1, 13, titlefont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.0f))); document.add( pdfPTable2.addCell(createCell("Company Name", 1, 1, companyfont,Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.0f))); document.add( pdfPTable2.addCell(createCell(gonssi, 1, 12, companyfont,Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.0f))); \t\t //Header data pdfPTable2.addCell(createCell("Document Number", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Voucher Number", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Voucher Date", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Expense Details Name", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Start Date", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("End Date", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Amortization period", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Invoice tax-free amount", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Monthly Amortization", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("This month's amortization", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Amortized months", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Cumulative amortization amount", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("Amortized balance", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); //Table body data pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("123456".toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); \t\t pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//Invoice tax-free amount TAX_FREE_AMT + =Double.parseDouble("123456"); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//Monthly amortization amount AMORTIZE_MONTH_ACCOUNT + =Double.parseDouble("123456"); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//This month’s amortization amount CURRENT_MONTH_ACCOUNT + =Double.parseDouble("123456"); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//Cumulative amortization amount TOTAL_AMORTIZE_ACCOUNT + =Double.parseDouble("123456"); pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//Amortized balance AMORTIZE_BALANCE + =Double.parseDouble("123456"); pdfPTable2.addCell(createCell("Total", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(TAX_FREE_AMT.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(AMORTIZE_MONTH_ACCOUNT.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(CURRENT_MONTH_ACCOUNT.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(TOTAL_AMORTIZE_ACCOUNT.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); pdfPTable2.addCell(createCell(AMORTIZE_BALANCE.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f)); document.add(pdfPTable2); document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return os; } /** * Multiple requirements to create one row and one column * @param cellName * @param row * @param col * @param font * @param shuiping * @param chuizhi * @param f * @return * @throws DocumentException * @throwsIOException */ public static PdfPCell createCell(String cellName,Integer row,Integer col,Font font,int shuiping,int chuizhi,float f) throws DocumentException, IOException{ PdfPCell cell = new PdfPCell(new Phrase(cellName, font)); cell.setUseBorderPadding(true); cell.setBorderWidth(f); cell.setVerticalAlignment(chuizhi);//Vertically centered System.out.println(col); if(row!=null){ cell.setRowspan(row); } if(col!=null & amp; & amp;col>1){ cell.setHorizontalAlignment(shuiping);//Horizontal centering cell.setColspan(col); }else{ cell.setHorizontalAlignment(shuiping); } return cell; } /** * Description: Upload files to FTP server * @param host FTP server hostname * @param port FTP server port * @param username FTP login account * @param password FTP login password * @param basePath FTP server base directory * @param filePath FTP server file storage path. For example, store by date: /2015/01/01. The path of the file is basePath + filePath * @param filename The file name uploaded to the FTP server * @param input input stream * @return Returns true if successful, otherwise returns false */ public static boolean uploadFile(String basePath,String filePath, String filename, InputStream input) { boolean result = false; try{ if (!ftp.changeWorkingDirectory("F://")) { String[] dirs = filePath.split("/"); String tempPath = basePath; for (String dir : dirs) { if (null == dir || "".equals(dir)) continue; tempPath + = "/" + dir; if (!ftp.changeWorkingDirectory(tempPath)) { if (!ftp.makeDirectory(tempPath)) { return result; } else { ftp.changeWorkingDirectory(tempPath); } } } \t\t\t } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.storeFile(filename, input)) { \t\t\t return result; }else{ result=true; System.out.println("Upload successful"); } \t\t }catch(Exception e){ e.printStackTrace(); } return result; } public static void main(String[] args) { ByteArrayOutputStream OS = T_LOG_RECORD_PREPAIDPDF("1","123","456"); //Save the file locally FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream("F:\aaaaa.pdf"); fileOutputStream.write(OS.toByteArray()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Upload to ftp server //Log in to the ftp server try { connect(); InputStream Input = new ByteArrayInputStream(OS.toByteArray()); uploadFile("","","",Input); } catch (Exception e) { e.printStackTrace(); } \t try { ftp.logout(); System.out.println("FTP server exited successfully"); } catch (IOException e) { System.out.println("FTP server failed to exit"); e.printStackTrace(); }finally{ if(ftp.isConnected()){ try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Log in to the ftp server * @throwsException */ public static void connect() throws Exception { try { ftp.setDefaultPort(8080);//port ftp.connect("127.0.0.1");//host ftp.setDataTimeout(60000000); // 10 minutes timeout ftp.setConnectTimeout(60000000); ftp.login("FTP_USER", "FTP_PWD"); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect();
// throw new RuntimeException(“FTP access denied”);
} } catch (Exception e) { e.printStackTrace(); \t\t } }
}