Exporting content to pdf without using iText - java

I have worked on exporting the html(table)contents to excel using table id. I have used content type like
response.getWriter().write(datatoexport);
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=test_file.xls");
response.getWriter().flush();
response.getWriter().close();
Here, datatoexport is the table id.
It is working fine with excel.
But, if I use content type as pdf like
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=test_file.pdf");
But, I am getting pdf file is corrupted. Any help?
Without using iText or other jars, How can I achieve it? Especially in IE 8

Before sending pdf file to output, you need to generate it on the server side.
To convert your file to PDF I recommend to use OpenOffice in headless mode and JODConverter.
To run OpenOffice in headless mode (in Windows) run the command (assume you have OpenOfficePortable, installed in C:\Apps:
"C:\Apps\OpenOfficePortable\OpenOfficePortable.exe" -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
As you have OpenOffice started in headless mode, run a simple working prototype using JODConverter library:
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import java.io.File;
import java.net.ConnectException;
public class JODConv {
public static void main(String[] args) throws ConnectException {
if (args.length!=2) {
System.out.println("Usage:\nJODConv <file-to-convert> <pdf-file>");
System.exit(0);
}
String sourceFilePath = args[0];
String destFilePath = args[1];
File inputFile = new File(sourceFilePath);
File outputFile = new File(destFilePath);
// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
// close the connection
connection.disconnect();
}
}

Related

SmartGWT ~ DSRequest download file

I am writing a server side class in smartGWT that fetches a record from a table and downloads a binary blob as a file from the database. The goal is to get the binary file attachment to download to local computer.
I was told that I could use DSRequest.getUploadedFile(attachment) to download the file but looking into it, it looks as though this method does not get an uploaded file from the database to download but gets a file to upload to the database.
Is there a way that I can get a file from the database and return it to the user as a download in server side code? We know we can do this in client side code but we would like to be able to do it on the server.
Here is how I am getting the record that contains the file I want to send to the user.
DSRequest dsReq = new DSRequest("table", "fetch");
dsReq.setCriteria("criteria", processFlowData.getVariableMap().get("critera"));
DataSource ds = dsReq.getDataSource();
DSResponse dsResp = ds.execute(dsReq);
if (dsResp.getStatus() < 0) {
//Handle Errors
} else {
if (!dsResp.getRecord().isEmpty()) {
//Download File Here
}
}
I am using Eclipse Kepler, SmartGWT, Java EE.
you could do something like this:
public static void downloadFile(DSRequest dsRequest, RPCManager rpcManager, HttpServletResponse servletResponse) throws Exception {
rpcManager.doCustomResponse();
ServletOutputStream outputStream = servletResponse.getOutputStream();
servletResponse.addHeader("Content-disposition", "attachment; filename=test.pdf");
servletResponse.setContentType("application/x-www-form-urlencoded");
OutputStream responseOutputStream = servletResponse.getOutputStream();
// write file to responseOutputStream
responseOutputStream.flush();
responseOutputStream.close();
}

How to write images, swf's, videos and anything else that is stored on a website to a file on my computer using streams

I'm trying to write a program that copies a website to my harddrive. This is easy enough to do just copying over the source and saving it as an html file, but In doing that you can't access any of the pictures, videos etc offline. I was wondering if there is a way to do this using an input/output stream and if so how exactly to do it...
Thanks so much in advance
If you have URL of the file to be downloaded then you can simply do it using apache commons-io
org.apache.commons.io.FileUtils.copyURLToFile(URL, File);
EDIT :
This code will download a zip file on your desktop.
import static org.apache.commons.io.FileUtils.copyURLToFile;
public static void Download() {
URL dl = null;
File fl = null;
try {
fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip");
dl = new URL("http://example.com/uploads/Screenshots.zip");
copyURLToFile(dl, fl);
} catch (Exception e) {
System.out.println(e);
}
}

Java write data to a file and download it?

I am new bi to Java, facing an issue with desktop application. I have to write data and output it as "data.txt"(means without writing file to a fixed location) and let the user download this file. I had searched a lot over internet but didn't get any proper solution. All suggestions are welcome.
Note : I am using NetBeans IDE 7.0.1
Save the data in a stream and then display a FileChooser dialog to let the user decide where to save the file to. Then write the stream to the selected file.
More on file choosers can be read here: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
Once you create your file on server you can then do a similar thing I did for sending image files to my clients (in my case it is a JSP but it really doesn't matter where your client is):
/**
* Writes file with a given path to the response.
* #param pathToFile
* #param response
* #throws IOException if there was some problem writing the file.
*/
public static void writeFile(String pathToFile, ServletResponse response) throws IOException {
try(InputStream is = new FileInputStream(pathToFile);
OutputStream out = new Base64OutputStream(response.getOutputStream());){
IOUtils.copy(is, out);
}
}
Those are the imports it uses:
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.io.IOUtils;
On the client (in your desktop app) you would use the same IOUtils to decode it from Base64 and then you can store it wherever you want.
For this bit actually #Matten gives a neat solution (+1).
I have example with JFileChooser but sorry still didn't get your point about the download thing.
BufferedOutputStream buff = null;
BufferedReader reader = null;
JFileChooser fileChooser;
File file;
fileChooser.showSaveDialog(this);
file = new File(fileChooser.getSelectedFile().toString());
file.createNewFile();
reader = new BufferedReader(new StringReader("String text"));
buff = new BufferedOutputStream(new FileOutputStream(file));
String str;
while ((str = reader.readLine()) != null) {
buff.write(str.getBytes());
buff.write("\r\n".getBytes());
}

Java Applet Download File

I am trying to build a java applet which downloads a file to the client machine. As a java application this code worked fine but when I tried as an applet it does nothing. I have signed the .jar file and am not getting any security error messages
The Code is:
import java.io.*;
import java.net.*;
import javax.swing.*;
public class printFile extends JApplet {
public void init(){
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL("http://www.google.com").openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("google.html");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
while(in.read(data,0,1024)>=0)
{
bout.write(data);
}
bout.close();
in.close();
} catch(IOException ioe){
}
}
}
Can anyone help?
FileOutputStream fos = new FileOutputStream("google.html");
Change that to:
File userHome = new File(System.getProperty("user.home"));
File pageOutput = new File(userHome, "google.html");
FileOutputStream fos = new FileOutputStream(pageOutput); //see alternative below
Ideally you would put the output in either of:
A sub-directory (perhaps based on the package name of the main class - to avoid collisions) of user.home. user.home is a place where the user is supposed to be able to read & create files.
A path as specified by the end user with the help of a JFileChooser.
See this question,
Self Signed Applet Can it access Local File Systems
I believe it will help you, you need to write your code to use PrivilegedAction.
http://docs.oracle.com/javase/1.4.2/docs/api/java/security/PrivilegedAction.html

Programmatic way to place a website into a new Word file... in Java

Is it possible to programmatically place the contents of a web page into a Word file?
To further complicate this, I'd like to do these steps in Java (using JNI if I must).
Here are the steps I want to do programmatically, followed by ways that I would do this manually today:
Provide a method with a URL (Manually: Open page in Firefox)
Copy the contents of that URL (Manually: Ctrl-A to select all)
Create a new Word document (Manually: Open Microsoft Word)
Paste the contents of the URL into Word (Manually: Ctrl-V to paste)
Save the Word file (Manually: Save the Word file)
you could do better imho downloading the file using HTTP then create a new word file using Apache POI and copying the HTTP stream inside the word file
HTMLUnit can be used to programmatically open the page (posing as Firefox if necessary), and Apache POI can be used to create a Microsoft Word file (in Word 97 format).
This article describes a way to manipulate MS-Word doc files from within Java, just using string replace, or XSLT.
As for grabbing the content of a URL, that is the simpler part of the task, which you can accomplish with something pretty simple.
import java.net.URL;
import java.net.URLConnection;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class util
{
public String HttpGet(String urlString)
{
String resultData= null;
try
{
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
java.lang.StringBuffer sb1= new java.lang.StringBuffer();
while ( (line = br.readLine()) != null)
sb1.append(line);
resultData= sb.toString();
mStatus= "gotprice";
}
catch (java.lang.Throwable e)
{
e.printStackTrace();
}
return resultData;
}
}

Categories

Resources