Ho risolto questo mio problema per il quale avevo utilizzato (malvolentieri) la soluzione mostrata sopra.
Non ho capito di preciso quale fosse il problema penso che l'errore da non compiere sia quello di aggiungere questa riga di codice prima di cominciare a creare il documento.
codice:
response.setContentType("application/pdf");
Il seguente codice crea un documento pdf senza memorizzarlo su filesystem e lo invia al client che lo visualizza direttamente in una nuova finestra del browser. Posto il tutto perchè ci ho perso la testa x parekkio tempo e mi farebbe piacere se servisse a qualcuno.
codice:
import com.lowagie.text.pdf.*;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.html.HtmlWriter;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Phrase;
import com.lowagie.text.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.util.MessageResources;
/**
* Creiamo il documento pdf dell'ordine.
*/
public class PrintOrderAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setHeader("pragma", "nocache");
response.setHeader("Transfer-Encoding","chunked");
response.addHeader("content-disposition", "filename=text.pdf");
response.setContentType("application/pdf");
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
PdfWriter.getInstance(document, response.getOutputStream());
// we add some meta information to the document
document.addAuthor("kibuz.com");
document.addSubject("You order.");
// we define a header and a footer
HeaderFooter header = new HeaderFooter(new Phrase("Ordine."), false);
HeaderFooter footer = new HeaderFooter(new Phrase("This is page "), new Phrase("."));
footer.setAlignment(Element.ALIGN_CENTER);
document.setHeader(header);
document.setFooter(footer);
// we open the document for writing
document.open();
document.add(new Paragraph("Hello world --->>>>"));
document.add(new Paragraph("varie scritte a scelta");
}
catch(DocumentException de) {
System.err.println(de.getMessage());
}
document.close();
return null;
}
}
Faccio notare che qualsiasi cosa (null o ActionForward) venga restituito la visualizzazione del file va sempre a buon fine.