Java JSF ile PDF dosyası oluşturma ve indirme kodu kullanımı örneği (Java JSF generate PDF file and provide download code usage example)

Java da JSF teknolojisi ile aşağıdak gibi pdf dosyası oluşturabilir ve oluşturulan bu pdf dosyasının kullanıcı tarafından indirilmesini sağlayabilirsiniz.

package net.yazilimcity.file.front.ui;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

@ManagedBean( name = "generatePdfBean" )
@ViewScoped
public class GeneratePdfBean {
	
	public void generateDownloadPDF() {
		String methodName = "generateDownloadPDF";
		
		String responseContentType = "application/pdf";
		String pdfFileName = "MyPdfFileName";
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
	    ExternalContext externalContext = facesContext.getExternalContext();
	    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
	    response.reset();
	    response.setContentType(responseContentType);
	    response.setHeader("Content-disposition", "attachment; filename=\"" + pdfFileName + ".pdf\"");
	    
		try {
				    
			Document document = new Document(PageSize.A4, 36, 36, 50, 50);
			BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp857", BaseFont.EMBEDDED);

			PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
			if (!document.isOpen()) {
				document.open();
	        }
			
			document.addAuthor("oguzhan.kinik");
			document.addTitle("my_title");

			Font captionFont = new Font(bf, 10, Font.BOLD);
			Paragraph captionParagraph = new Paragraph("www.yazilimcity.net", captionFont);
			captionParagraph.setAlignment(Element.ALIGN_CENTER);
			document.add(captionParagraph);			
			document.close();
			writer.close();
			
			facesContext.responseComplete();       

			System.out.println("finished");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
	
}

Arayüzden tetiklemek için ise

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"> 

<h:head></h:head> 
<body> 
<h:form>		
	<h:commandButton value="PDF İndir" actionListener="#{generatePdfBean.generateDownloadPDF()}" 
		icon="ui-icon-arrowthick-1-s" ajax="false" />
</h:form>		    				
</body> 
</html>

Dinamik olarak hafızada dosyanın tutulması ile ise şöyle yazılabilir.

package net.yazilimcity.file.front.ui;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

@ManagedBean( name = "generatePdfBean" )
@ViewScoped
public class GeneratePdfBean {
	
	public void generateDownloadPDF() {
		String methodName = "generateDownloadPDF";
		
		String responseContentType = "application/pdf";
		String pdfFileName = "MyPdfFileName";
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
	    ExternalContext externalContext = facesContext.getExternalContext();
	    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
	    response.reset();
	    response.setContentType(responseContentType);
	    response.setHeader("Content-disposition", "attachment; filename=\"" + pdfFileName + ".pdf\"");
	    
		try {
				    
			ByteArrayOutputStream baos = generateDocumentInMemory();
			baos.writeTo(response.getOutputStream());

			response.getOutputStream().close();

			facesContext.responseComplete();
			System.out.println("finished");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());

			pdfFileName = e.getMessage();
		    	response.setHeader("Content-disposition", "attachment; filename=\"" + pdfFileName + ".zip\"");
		    	return;
		}
	}


	private ByteArrayOutputStream generateDocumentInMemory() throws Exception {
		String methodName = "generateDocumentInMemory";
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
//		try {
			String couldNotBeReached = "Veriye Ulaşılamadı";
			
			Document document = new Document(PageSize.A4, 36, 36, 50, 50);
			BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp857", BaseFont.EMBEDDED);

			// put document to baos
	        PdfWriter writer = PdfWriter.getInstance(document, baos);
			if (!document.isOpen()) {
				document.open();
	        }
			
			document.addAuthor("oguzhan.kinik");
			document.addTitle("my_title");

			Font captionFont = new Font(bf, 10, Font.BOLD);
			Paragraph captionParagraph = new Paragraph("www.yazilimcity.net", captionFont);
			captionParagraph.setAlignment(Element.ALIGN_CENTER);
			document.add(captionParagraph);			
			document.close();

			writer.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//			System.out.println(e.getMessage());
//			MyFacesMessage.exceptionMessage(methodName + "::" + e.getMessage());
//		}

		return baos;
	}
	
}

Share on Facebook0Tweet about this on TwitterShare on Google+0Share on StumbleUpon0Share on Reddit0

Leave a Reply


*