I generated pdf file using velocity templates but i am not able to put images in my pdf.
I've try using external and internal images but the picture still not displaying.
I also have tried this tutorial but still not showing images in generated pdf.
`File f = new File("D:\\uploadfile\\assets\\test.png");
FileInputStream fin = new FileInputStream(f);
byte imagebytearray[] = new byte[(int)f.length()];
fin.read(imagebytearray);
String imagetobase64 = Base64.encodeBase64String(imagebytearray);
fin.close();
logger.info("data: "+imagetobase64);
context.put("image", imagetobase64);
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge(context, writer);
/* show the World */
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos = generatePdf(writer.toString());
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(baos.toByteArray().length);
return new HttpEntity<byte[]>(baos.toByteArray(), header);`
On vm template i try, but the images still not diplayed
<img src="data:image/png;base64,$image" border="0" width="50" height="50"/>
<img src="https://www.jamasoftware.com/media/gravatar/jama-avatar.png"/>
Any help or sugestion?
Thanks
Related
PdfReader reader = new PdfReader(sourceXfaPath);
PdfWriter writer = new PdfWriter(exportPdf);
PdfDocument pdfDoc = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode());
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
XfaForm xfa = form.GetXfaForm();
xfa.FillXfaForm(new FileStream(exportXfaXml,FileMode.Open));
xfa.Write(pdfDoc);
pdfDoc.Close();
reader.Close();
codes are above:
but it doesn't create pdf document, I'm not sure why it doesn't create it.
I just tried xfa.FillXfaForm(new FileStream(exportXfaXml,FileMode.Open)); to xfa.FillXfaForm(XmlReader.Create(path));
but it shows me same error
public void customGenerate(string sourceFilePath, string destinationtFilePath, string replacementXmlFilePath)
{
PdfReader pdfReader = new PdfReader(sourceFilePath);
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(pdfReader, ms, '\0', true))
//using (PdfStamper stamper = new PdfStamper(pdfReader, ms))
{
XfaForm xfaForm = new XfaForm(pdfReader);
XmlDocument doc = new XmlDocument();
doc.Load(replacementXmlFilePath);
xfaForm.DomDocument = doc;
xfaForm.Changed = true;
XfaForm.SetXfa(xfaForm, stamper.Reader, stamper.Writer);
stamper.Close();
}
var bytes = ms.ToArray();
System.IO.File.WriteAllBytes(destinationtFilePath, bytes);
ms.Close();
}
pdfReader.Close();
}
This is my code to add Javacript to XFA PDF.
I'm going to add JavaScript[handle button , checkbox] to XFA pdf with avoid signature.
For one of the implementation, from Java code I am hitting labelary Rest service to convert ZPL formatted code to Image.
I am able to successfully fetch the response. But I am not able to convert the HttpResponse to image file.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost "http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/");
byte[] byteArray = Base64.decodeBase64(base64Val.getBytes());
String decodedString = new String(byteArray);
StringEntity requestEntity;
try {
requestEntity = new StringEntity(decodedString);
requestEntity.setContentType("application/x-www-form-urlencoded");
post.setEntity(requestEntity);
HttpResponse response = client.execute(post);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
#Need suggestions to convert BufferReader to Image
}
Post referring the suggested answer, code looks like:
HttpResponse response = client.execute(post);
InputStream inStream = response.getEntity().getContent();
String dataString = convertStreamToString(inStream);
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
File outputfile = new File("myImage.png");
ImageIO.write(image, "png", outputfile);
use this byte to image converter. past value in datastring and check whether you get the image.
I want to fetch video from mongodb than it should play that video up to video size, but its playing only some second, i gave maxUploadSize is 20mb and maxInMemorySize also 20mb,but on the jsp page, its fetching only 1mb video even video size more than 1mb.
I am not getting what to do, video should play full according to video size
here is Controller
#RequestMapping(value = "/welcome-video-controller/{videoObj}", produces = "video/webm")
#ResponseBody
public ResponseEntity<byte[]> getVideoForLoginPage(#PathVariable String videoObj, HttpServletResponse response)
throws IOException {
LOG.info("Entry :: getVideoForPost");
BufferedImage bufferedVideoForPost = null;
URL resourcePath = null;
byte[] videoArray = null;
ResponseEntity<byte[]> result = null;
LOG.info("videoObj-->" + videoObj);
File videoFromMongo = new File(VIDEO_FROM_PATH + videoObj);
GridFSDBFile videoFile = MongoUtility.getVideoFileFromMongo(videoObj);
videoFile.writeTo(videoFromMongo);
bufferedVideoForPost = ImageIO.read(videoFromMongo);
videoFile.getInputStream();
HttpHeaders headers = new HttpHeaders();
headers.setContentLength((int) videoFile.getLength());
videoArray = new byte[(int) videoFile.getLength()];
result = new ResponseEntity<byte[]>(videoArray, headers, HttpStatus.OK);
videoFile.getInputStream().read(videoArray);
LOG.info("videoArray-->" + videoArray);
LOG.info("videoArray size-->" + videoArray.length);
return result;
}
and this is html codding
<c:set value="${videoPostDetail.videoNames}" var="videoObj" />
<c:if test="${videoObj ne ''}">
<video width="96%" height="220" controls id="sideVideo">
<source src='/SocialNetworkingApp/welcome-video-controller/${videoObj}.do' type='video/webm'>
</video>
</c:if>
it should play complete video,i tried lot but nothing is working, plz tell what's problem,
I got the solution, actually problem was the chunk size, i dint set chunk size of file and by default chunkSize was less than 1 mb,
now i added this line into the code gfsFile.setChunkSize(uploadVideoFile.length()); and its working fine.
public static void saveVideoIntoMongo(File uploadVideoFile, String videoFilePath, String newVideoFileName)
throws IOException {
LOG.info("Entry :: saveVideoIntoMongo");
LOG.info("videoFilePath-->" + videoFilePath);
LOG.info("newVideoFileName-->" + newVideoFileName);
LOG.info("uploadVideoFile-->" + uploadVideoFile);
DB db = getMongoDBInstance("videoDb");// later on take it from the properties file instead of hardcoding
GridFS gfsPhoto = getGridFSForFiles(db, "video");
if (!("").equals(newVideoFileName)) {
GridFSInputFile gfsFile = gfsPhoto.createFile(uploadVideoFile);
gfsFile.setChunkSize(uploadVideoFile.length());//setting chunkSize
gfsFile.setFilename(newVideoFileName);
gfsFile.save();
}
LOG.info("Exit :: saveVideoIntoMongo");
}
I need to insert an image into an existing pdf at a specific location. I tried the answer at this question. But whatever different ways I do the image is being inserted at (0,0) position (bottom left corner). I tried another approach where instead of using stream I used Document class in iTextSharp as shown here. Now I am able to place the image at the desired position but this method is creating a new document with just this image. Most of the articles I searched are using PdfReader and PdfStamper so I think this is the recommended way. Any help is appreciated. Posting below code for both the methods I tried.
PdfStamper method
private void AddImage(string filePath)
{
string imageURL = #"ImagePath\Image.jpg";
using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
using (Stream outputPdfStream = new FileStream(#"ResultingPdfPath\Abcd.pdf", FileMode.Create, FileAccess.ReadWrite))
{
Image image = Image.GetInstance(inputImageStream);
image.ScaleToFit(100, 100);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
PdfContentByte content = stamper.GetUnderContent(1);
image.SetAbsolutePosition(100f, 150f);
content.AddImage(image);
stamper.Close();
reader.Close();
}
}
Document class method
private void TestMessage(string filePath)
{
string imageURL = #"ImagePath\Image.jpg";
Document doc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Open));
doc.Open();
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
jpg.ScaleToFit(140f, 120f);
jpg.SetAbsolutePosition(100, 100);
jpg.SpacingBefore = 10f;
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_LEFT;
doc.Add(jpg);
doc.Close();
}
Let me know if you need further information.
I adapted your method to accept variable out paths and positions and tested it with iTextSharp 5.5.7 like this:
[TestFixture]
class TestInsertImage
{
/// iText stamp image on top not always working
/// http://stackoverflow.com/questions/33898280/itext-stamp-image-on-top-not-always-working
///
[Test]
public void AddStampToTestPdf()
{
Directory.CreateDirectory(#"C:\Temp\test-results\content\");
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-100-150.pdf", 100f, 150f);
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-150-100.pdf", 150f, 100f);
}
private void AddImage(string filePath, string outPath, float x, float y)
{
string imageURL = #"c:\Repo\GitHub\testarea\itext5\src\test\resources\mkl\testarea\itext5\layer\Willi-1.jpg";
using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
using (Stream outputPdfStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
{
Image image = Image.GetInstance(inputImageStream);
image.ScaleToFit(100, 100);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
PdfContentByte content = stamper.GetUnderContent(1);
image.SetAbsolutePosition(x, y);
content.AddImage(image);
stamper.Close();
reader.Close();
}
}
}
The results are included below.
As you see, the positioning information clearly are respected, and the image is definitely not always at the bottom left corner.
If this indeed does not work for the OP, he is keeping information from us required to help him.
Multipage-stamp-Image-100-150.pdf
Created using
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-100-150.pdf", 100f, 150f);
Multipage-stamp-Image-150-100.pdf
Created using:
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-150-100.pdf", 150f, 100f);
I'm facing with character encoding issue while exporting PDF with using iText PDF Library despite I set exporter's CHARACTER_ENCODING property to UTF-8 as I added below :
Class clazz = Class.forName(User.class);
Document document = new Document();
PdfWriter.getInstance(document, baos);
document.open();
addMetaData(document);
addDate(document);
addTitlePage(document, className);
addEmptyLineToDocument(document, 2);
addContent(document, className, clazz);
addEmptyLineToDocument(document, 2);
addSignature(document);
return document;
Here's the addContent method sample:
private static FontFamily fontFamily = FontFamily.TIMES_ROMAN;
Font fontNormal10 = new Font(fontFamily, 10, Font.NORMAL);
Paragraph paragraph = new Paragraph();
Chunk chunk = new Chunk("Here is the list of " + className, fontNormal10);
paragraph.add(chunk);
// continues
Then I write the document with ServletOutputStream :
// **document** => which I created and returned above
document.close();
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename=" + outputFileName);
response.setContentType("application/pdf; charset=UTF-8");
response.setContentLength(baos.size());
ServletOutputStream outputStream = response.getOutputStream();
baos.writeTo(outputStream);
outputStream.flush();
outputStream.close();
I also added JVM parameter "file.encoding=UTF-8" too..
Set response content type with "charset=UTF-8;" property..
Any ideas? Thanks in advance..