Insert an image into an existing pdf document using iText Sharp - image

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);

Related

Filling XFA data to xfa form pdf with ITEXT 7 in C#

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.

Display image after capturing in Xamarin

I have been trying to make an application that invokes camera through page rendering. I have used Custom Renderer from Xamarin. My problem is I need to send the picture to the other page/activity in the "Native" after clicking, but currently it is saving the picture in the gallery of the device.
For example: I click the image and then the image gets displayed with the message "Do you want to save it?". This has to be done in native rather than PCL. I have been trying through intent but that doesn't work.
All my code right now doing is saving the image to the gallery.
try
{
var absolutePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).AbsolutePath;
var folderPath = absolutePath + "/Camera";
var filePath = System.IO.Path.Combine(folderPath, string.Format("photo_{0}.jpg", Guid.NewGuid()));
var fileStream = new FileStream(filePath, FileMode.Create);
await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 100, fileStream);
fileStream.Close();
image.Recycle();
// imageByte = ((byte[])image);
var intent = new Android.Content.Intent(Android.Content.Intent.ActionMediaScannerScanFile);
var file = new Java.IO.File(filePath);
var uri = Android.Net.Uri.FromFile(file);
intent.SetData(uri);
//intent.PutExtra("image", imageByte);
MainActivity.Instances.SendBroadcast(intent);
}
Solved it. Passing bitmap through intent.
Activity 1:
byte[] imageByte;
var image = textureView.Bitmap;
MemoryStream memStream = new MemoryStream();
// ByteArrayOutputStream _bs = new ByteArrayOutputStream();
await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 100, memStream);
imageByte = memStream.ToArray();
Intent i = new Intent(this.Context, typeof(CameraDisplay));
i.PutExtra("image", imageByte);
activity.StartActivity(i);
Activity 2:
byte[] Image = Intent.GetByteArrayExtra("image");
imageView = FindViewById(Resource.Id.imageView1);
Bitmap bitmap = BitmapFactory.DecodeByteArray(Image, 0, Image.Length);
imageView.SetImageBitmap(bitmap);

How to render java.awt.Graphics2D in PdfDocument using iText7?

//writer is an instance of PdfWriter
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate temp = contentByte.createTemplate(width ,height);
Graphics2D g2d = temp.createGraphics(width, height);
Rectangle2D r2d = new Rectangle2D.Double(0,0,width ,height);
//chart is an instance of JFreeChart and info is the information required for rendering a chart in JFreeChart
chart.draw(g2d,r2d,info);
img = Image.getInstance(temp);
document.add(img);
This is the code in iText 5. How to obtain the Graphics2D object using Itext7?
Ran into the same issue updating the version and this was the solution I ended up with:
document.add(convertChartToImage(chart));
Where convertChartToImage(...) is the following:
private Image convertChartToImage(JFreeChart chart) throws IOException {
Image result = null;
BufferedImage original = chart.createBufferedImage(WIDTH, HEIGHT);
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
ImageIO.write(original, "png", os);
os.flush();
ImageData image = ImageDataFactory.create(os.toByteArray());
result = new Image(image);
}
return result;
}
Hope this helps. There might be a better way.

Maintain orientation when resizing image with opencv

FYI, I'm new to OpenCV. I'm creating an AWS Lambda function that will utilize OpenCV 2.4 to resize images that I have in S3. S3 generates an event that launches my Lambda function when an image is uploaded to my source bucket. The lambda function successfully resizes the images and stores the resized image to the target bucket with the same object key as the original image. I have test images that where taken with a digital camera and some from an Android phone. What I've noticed is if I have an image from the phone that was taken in portrait the image in the source bucket is oriented correctly but the resized version in the target bucket is orientated incorrectly. Images taken in portrait orientation are converted to landscape. How do I maintain the orientation when resizing images. Below is the code I'm using.
public Object handleRequest(S3Event input, Context context) {
OpenCV.loadLibrary();
for (S3EventNotificationRecord record : input.getRecords()) {
String bucketName = record.getS3().getBucket().getName();
S3ObjectEntity entity = record.getS3().getObject();
String objectKey = entity.getUrlDecodedKey();
context.getLogger().log("ObjectKey: " + objectKey);
String fileExtension = objectKey.substring(objectKey.lastIndexOf("."));
context.getLogger().log("file extension: " + fileExtension);
S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, objectKey));
InputStream objectData = object.getObjectContent();
ObjectMetadata objectMetadata = object.getObjectMetadata();
// Process the objectData stream.
int nRead;
byte[] data = new byte[16 * 1024];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
while ((nRead = objectData.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
byte[] bytes = buffer.toByteArray();
Mat srcImage = Highgui.imdecode(new MatOfByte(bytes), Highgui.CV_LOAD_IMAGE_UNCHANGED);
Mat resizedImage = new Mat();
Imgproc.resize(srcImage, resizedImage, new Size(0,0), 0.1, 0.1, Imgproc.INTER_AREA);
MatOfByte resizedMatOfByte = new MatOfByte();
Highgui.imencode(fileExtension, resizedImage, resizedMatOfByte);
byte[] bytesToWrite = resizedMatOfByte.toArray();
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(bytesToWrite.length);
meta.setContentType(objectMetadata.getContentType());
PutObjectRequest putRequest = new PutObjectRequest(Configuration.MINIMIZED_ARTIFACT_BUCKET, objectKey, new ByteArrayInputStream(bytesToWrite), meta);
s3Client.putObject(putRequest);
objectData.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return null;
}

.net mvc3 iTextSharp how to add image to pdf in memory stream and return to browser

I have a .pdf file stored in my database, and I have a signature file (.png) stored in my database. I am trying to use iTextSharp to add the signature image to the .pdf file, and display the result to the browser.
Here is my code:
byte[] file = Repo.GetDocumentBytes(applicantApplication.ApplicationID, documentID);
byte[] signatureBytes = Repo.GetSignatureBytes((Guid)applicantApplicationID, signatureID);
iTextSharp.text.Image signatureImage = iTextSharp.text.Image.GetInstance(signatureBytes);
iTextSharp.text.Document document = new iTextSharp.text.Document();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(file, 0, file.Length, true, true))
{
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
signatureImage.SetAbsolutePosition(200, 200);
signatureImage.ScaleAbsolute(200, 50);
document.Add(signatureImage);
document.Close();
return File(ms.GetBuffer(), "application/pdf");
}
The page loads, and there is a .pdf with a signature, but the original document is nowhere to be found. It looks like I'm creating a new .pdf file and putting the image in there instead of editing the old .pdf file.
I have verified that the original .pdf document is being loaded into the "file" variable. I have also verified that the length of the MemoryStream "ms" is the same as the length of the byte[] "file".
I ended up doing something like this in my repository:
using (Stream inputPdfStream = new MemoryStream(file, 0, file.Length, true, true))
using (Stream inputImageStream = new MemoryStream(signatureBytes, 0, signatureBytes.Length, true, true))
using (MemoryStream outputPdfStream = new MemoryStream())
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var cb = stamper.GetOverContent(1);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(400, 100);
image.ScaleAbsolute(200, 50);
cb.AddImage(image);
stamper.Close();
return outputPdfStream.GetBuffer();
}
I adapted it from a few other answers on StackOverflow

Resources