Criar pdf a partir de byte[]

9 respostas
A

Tem como eu criar pdf a partir de um vetor de bytes?

9 Respostas

B

O que este array de bytes representa? uma imagem? uma string?

A

Eu tenho uma tabela documento que tem dois campos um text com o conteudo texto do pdf que uso o hibernate search para indexar e fazer busca fulltext e um outro campo blob onde salvo o array de bytes que forma aquele documento.

Esse vetor de byte representa o conteúdo binário do arquivo pdf que foi armazenado.
É o processo de recuperação do pdf para exibi-lo na tela.
Ideia de como fazer isso?

F

Acho que normal. Escreve no arquivo físico no filesystem com os streams do java. Depois retorna esse arquivo.

A

Salva com a extensão .pdf apenas?
Tentei fazer isso e o arquivo veio em branco…

F

Mas o arquivo tava com que tamanho, em bytes? Acho que a extensão não importa, importa mesmo é seu conteúdo escrito em bytes.

A

O código que uso para gerar o arquivo é esse...O pdf que ele gera vem em branco sendo que o vetor de bytes está com conteúdo...

public static File convertInputStreamToFile(InputStream inputStream,
			String nomeArquivo) {

		try {
			File f = new File("c:\\desenvolvimento\\pdf\\"+nomeArquivo + ".pdf");
			OutputStream out = new FileOutputStream(f);
			byte buf[] = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			out.close();
			inputStream.close();
			f.createNewFile();
			return f;
		}
		catch (IOException e) {
			throw new UtilException(e);
		}
	}

new ByteArrayInputStream(documentoModel.getArquivoFisico())
D

[color=green]Olá, acredito que o código abaixo possa te ajudar:[/color]

ServletOutputStream servletOutputStream = res.getOutputStream();
    	
File reportFileJasper = "C:\\ ... \\teste.jasper";
byte[] bytes = null;

try {
        bytes = JasperRunManager.runReportToPdf(reportFileJasper.getPath(), parametros, con);

        res.setContentType("application/pdf");
        res.setContentLength(bytes.length);

        servletOutputStream.write(bytes, 0, bytes.length);
        servletOutputStream.flush();
        servletOutputStream.close();
} catch (JRException e) {
       	StringWriter stringWriter = new StringWriter();
       	PrintWriter printWriter = new PrintWriter(stringWriter);
       	e.printStackTrace(printWriter);
       	res.setContentType("text/plain");
       	res.getOutputStream().print(stringWriter.toString());
};
[color=green]Até...[/color]
J

Antônio uma pergunta, você tá utilizando Oracle para armazenar o binário?

R

o link abaixo dá a resposta...

[url]http://www.programcreek.com/2009/02/java-convert-a-file-to-byte-array-then-convert-byte-array-to-a-file/#comments[/url]

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class genFile {
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
        File file = new File("java.pdf");
 
        FileInputStream fis = new FileInputStream(file);
        //System.out.println(file.exists() + "!!");
        //InputStream in = resource.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] bytes = bos.toByteArray();
 
        //below is the different part
        File someFile = new File("java2.pdf");
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }
}
Criado 24 de junho de 2008
Ultima resposta 22 de ago. de 2009
Respostas 9
Participantes 6