将itext pdf另存为blob,但不存在. [英] Save itext pdf as blob without physical existence.
问题描述
我正在使用此代码使用iText生成PDF.首先,它将HTML创建为PDF,然后将其转换为字节数组,BLOB或字节数组. 我不想在服务器上创建pdf的任何物理存储.首先,我想使用itext将HTML转换为PDF的blob,然后,我要将那个blob存储在我的DB中(我将完成在DB中的存储).
I am using this code to generate PDF using iText. First it creates HTML to PDF after that it converts that PDF in byte array or in BLOB or in byte array. I dont want to create any physical stores of pdf on my server. First i want to convert HTML to blob of PDF using itext, And after that i want to store that blob in my DB(Stores in DB i will done).
String userAccessToken=requests.getSession()
.getAttribute("access_token").toString();
Document document = new Document(PageSize.LETTER);
String name="/pdf/invoice.pdf";
PdfWriter pdfWriter = PdfWriter.getInstance
(document, new FileOutputStream(requests.getSession().getServletContext().getRealPath("")+"/assets"+name));
document.open();
document.addAuthor("Real Gagnon");
document.addCreator("Real's HowTo");
document.addSubject("Thanks for your support");
document.addTitle("Please read this ");
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
//data is an html string
String str = data;
worker.parseXHtml(pdfWriter, document, new StringReader(str));
document.close();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfWriter.getInstance(document, byteArrayOutputStream);
byte[] pdfBytes = byteArrayOutputStream.toByteArray();
link=name;
System.out.println("Byte array is "+pdfBytes);
问题:-使用itext将html转换为pdf BLOB,而没有PDF的物理存在.
PROBLEM:- Convert html to pdf BLOB using itext, Without physical existence of PDF.
推荐答案
此问题的另一个答案几乎是正确的,但不完全正确.
The other answer to this question is almost correct, but not quite.
创建PdfWriter
时可以使用任何OutputStream
.如果要完全在内存中创建文件,则可以使用如下所示的ByteArrayOutputStream
:
You can use any OutputStream
when you create a PdfWriter
. If you want to create a file entirely in memory, you can use a ByteArrayOutputStream
like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, baos);
document.open();
// add stuff
document.close();
byte[] pdf = baos.toByteArray();
简而言之:首先创建一个ByteArrayOutputStream
,然后将此OutputStream
传递给PdfWriter
,然后在关闭文档后,可以从OutputStream
获取字节.
In short: you first create a ByteArrayOutputStream
, you pass this OutputStream
to the PdfWriter
and after the document is closed, you can get the bytes from the OutputStream
.
(在另一个答案中,没有办法检索字节.而且:重要的是,不要在关闭文档之前尝试检索字节.)
(In the other answer, there was no way to retrieve the bytes. Also: it is important that you don't try to retrieve the bytes before the document is closed.)
这篇关于将itext pdf另存为blob,但不存在.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!