Java JSF ile Zip dosyası oluşturma içerisine Pdf dosyası ekleme ve indirme işlemi kodu kullanımı örneği (Java JSF generate pdf file to put zip file and download code usage example)

Java da JSF teknoloji ile aşağıdak gibi zip dosyası oluşturabilir, pdf dosyası oluşturabilir ve oluşturulan bu pdf dosyasını zip içerisine ekleyebilir ve zip dosyasınının kullanıcı tarafından indirilmesini sağlayabilirsiniz.

package net.yazilimcity.file.front.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

@ManagedBean( name = "generateZipBean" )
@ViewScoped
public class GenerateZipBean {

	public void generateDownloadZIP() {
		
		String responseContentType = "application/octet-stream";
		String zipFileName = "ZIP_FILE_NAME";

		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();
		HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
		response.reset();
		response.setContentType(responseContentType);
		response.setHeader("Content-disposition", "attachment; filename=\"" + zipFileName + ".zip\"");

		try {
			Document document = new Document(PageSize.A4, 36, 36, 50, 50);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			// generate in application webapp directory
			//PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("PdfTest.pdf"));
			// generate in memeory
			PdfWriter writer = PdfWriter.getInstance(document, baos);
			if (!document.isOpen()) {
				document.open();
	        }

		document.add(new Paragraph("www.yazilimcit.net ... my paragraph"));
		document.close();
		writer.close();

		ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

		ZipEntry zipEntry = new ZipEntry("internalFile.pdf"); 
		zos.putNextEntry(zipEntry);

          	InputStream input = null;
		input = new ByteArrayInputStream(baos.toByteArray());
            
            	int len;
		byte[] buffer = new byte[1024];
    		while ((len = input.read(buffer)) > 0) {
    			zos.write(buffer, 0, len);
    		}
    		input.close();
		zos.closeEntry();
		zos.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="ZIP İndir" actionListener="#{generateZipBean.generateDownloadZIP()}" 
			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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

@ManagedBean( name = "generateZipBean" )
@ViewScoped
public class GenerateZipBean {

	public void generateZipFile() {
		String methodName = "generateZipFile";

		if(selectedMyObjects.size() == 0) {
			MyFacesMessage.displayWarnMessage("Kayıt seçmelisiniz.");
			return;
		}
		MyObject myObject = new MyObject();
		
		String responseContentType = "application/octet-stream";
		String zipFileName = "My_Zip_File_Name";
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
	    ExternalContext externalContext = facesContext.getExternalContext();
	    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
	    response.reset();
	    response.setContentType(responseContentType);
	    response.setHeader("Content-disposition", "attachment; filename=\"" + zipFileName + ".zip\"");
	   
		try {
			
			ServletOutputStream responseOutputStream = response.getOutputStream();
			ZipOutputStream zos = new ZipOutputStream(responseOutputStream);
			for(int i=0; i<selectedObjects.size(); i++) {
				myObject = selectedAppointments.get(i);
				
				// generate zip file entry
				String pdfFileName = myObject.getDescription();
				ZipEntry zipEntry = new ZipEntry(pdfFileName + ".pdf");
	            zos.putNextEntry(zipEntry);
	            
	            // generate document for zip content in memory
	            ByteArrayOutputStream baos = generateDocumentInMemory(myObject);
				
				// write in memory baos to zip
				InputStream inputStrm = new ByteArrayInputStream(baos.toByteArray());
				baos.flush();
				baos.close();
				
	            int bytesread = 0, bytesBuffered = 0;
				byte[] buffer = new byte[4096];
	    		while ((bytesread = inputStrm.read(buffer)) > -1) {
	    			zos.write(buffer, 0, bytesread);
	    			 bytesBuffered += bytesread;
	                 if (bytesBuffered > 1024 * 1024) { //flush after 1mb
	                     bytesBuffered = 0;
	                     zos.flush();
	                 }
	    		}
	    		zos.closeEntry();
				zos.flush();
	    		inputStrm.close();
			}
			zos.flush();        
			zos.close();
			responseOutputStream.close();
			
			
	 		facesContext.responseComplete();       

			System.out.println("finished");
			MyFacesMessage.debugMessage(methodName + "::" + "finished");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			MyFacesMessage.exceptionMessage(methodName + "::" + e.getMessage());
			
			zipFileName = e.getMessage();
		    response.setHeader("Content-disposition", "attachment; filename=\"" + zipFileName + ".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


*