How can I convert a PDF into a web-browsable image? - pdf

I need to create an online viewer which converts PDF files into browsable images, like http://view.samurajdata.se/. I would like to do this in Grails. Does Grails have any plugins for this?

that's is possible by download PDFRenderer.jar fie and writing code is below
downloadedfile = request.getFile('sourceFile');
println "download file->"+downloadedfile
File destFile=new File('web-app/source-pdf/'+downloadedfile+'.pdf');
if(destFile.exists()){
destFile.delete();
}
File file = null;
try{
file = new File('web-app/source-pdf/'+downloadedfile+'.pdf');
downloadedfile.transferTo(file)
println "file->"+file
}catch(Exception e){
System.err.println("File Already Use")
//out.close();
}
File imageFile=new File("web-app/pdf-images");
if(imageFile.isDirectory())
{
String[] list=imageFile.list()
for(int i=0;i<list.length;i++){
File img=new File("web-app/pdf-images/"+i+".png")
img.delete()
}
}
//response.setContentType("image/png");
// response.setHeader("Cache-control", "no-cache");
RandomAccessFile raf;
BufferedImage[] img;
// response.setContentType("image/png");
// response.setHeader("Cache-control", "no-cache");
file=new File('web-app/source-pdf/'+downloadedfile+'.pdf');
try {
raf = new RandomAccessFile(file, "rws");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
// draw the first page to an image
int num=pdffile.getNumPages();
img=new BufferedImage[num]
for(int i=0;i<num;i++)
{
PDFPage page = pdffile.getPage(i);
//get the width and height for the doc at the default zoom
int width=(int)page.getBBox().getWidth();
int height=(int)page.getBBox().getHeight();
Rectangle rect = new Rectangle(0,0,width,height);
int rotation=page.getRotation();
Rectangle rect1=rect;
if(rotation==90 || rotation==270)
rect1=new Rectangle(0,0,(int)rect.height,(int)rect.width);
//generate the image
img[i] = (BufferedImage)page.getImage(
width,height , //width & height
rect1, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
ImageIO.write(img[i], "png",new File("web-app/pdf-images/"+i+".png"));
}
// out.close();
}
catch (FileNotFoundException e1) {
System.err.println(e1.getLocalizedMessage());
} catch (IOException e) {
System.err.println(e.getLocalizedMessage());
}
file = null;
render(view:'save',model:[images:img])

Related

File provider error to receive pdf from another program

`# Dears, this class works well to receive PDF files from another application on below Android 6, but it gives an error for Android uper 6
` #RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public int ExtractImage(Intent intent) {
try {
String filepath = null;
if (intent != null) {
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_VIEW.equals(action) && type.endsWith("pdf")) {
Uri file_uri = intent.getData();
if (file_uri != null) {
filepath = file_uri.getPath();
}
} else if (Intent.ACTION_SEND.equals(action) && type.endsWith("pdf")) {
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (uri != null) {
filepath = uri.getPath();
}
}
}
File file = new File(filepath);
PdfRenderer renderer = null;
Bitmap bm;
try {
renderer = new PdfRenderer(ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_READ_ONLY));
} catch (Exception e) {
}
assert renderer != null;
final int pageCount = renderer.getPageCount();
totalPage = pageCount;
for (int i = 0; i < pageCount; i++) {
PdfRenderer.Page page = renderer.openPage(i);
// Create a bitmap and canvas to draw the page into
int width = 570;
int zarib = 570 / (page.getWidth() + 1);
int height = (page.getHeight() * 2) + 1;
heightArray.add(i, height);
// Create a bitmap and canvas to draw the page into
bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// Create canvas to draw into the bitmap
Canvas c = new Canvas(bm);
// Fill the bitmap with a white background
Paint whiteBgnd = new Paint();
whiteBgnd.setColor(Color.WHITE);
whiteBgnd.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, width, height, whiteBgnd);
// paint the page into the canvas
page.render(bm, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
// Save the bitmap
OutputStream outStream = null;
try {
outStream = new
FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/printDo2ta" + i + ".png");
} catch (Exception e) {
e.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.PNG, 80, outStream);
try {
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
page.close();
}
} catch (Exception e) {
runOnUiThread(() -> Toast.makeText(getBaseContext(),
"خطا در پردازش فایل: " + e.getMessage(),
Toast.LENGTH_SHORT).show());
}
return totalPage;
}
I inserted this code in AndroidManifest.xml
`<provider
android:name="androidx.core.content.FileProvider"
android:authorities="ir.myproject.test.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>`
`
And I made the class provider_paths.xml
`<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>`
I don't know what else I need to change to make it work on Android 8
please help me`

iTextSharp Document Isn't Working After Deployment

i'm using iTextSharp to create a pdf document then add it as an attachment to send an email using SendGrid.
The code is working locally but after deploying the project in Azure this function stopped working for some reason. I tried to analyze the problem and i think that the document didn't fully created of attached due to the connection. I can't pin point the exact issue to solve it. Any opinions or discussion is appreciated.
Action:
public async Task<IActionResult> GeneratePDF(int? id, string recipientEmail)
{
//if id valid
if (id == null)
{
return NotFound();
}
var story = await _db.Stories.Include(s => s.Child).Include(s => s.Sentences).ThenInclude(s => s.Image).FirstOrDefaultAsync(s => s.Id == id);
if (story == null)
{
return NotFound();
}
var webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "dump"); //folder name
try
{
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
string usedFont = Path.Combine(webRootPath + "\\fonts\\", "arial.TTF");
BaseFont bf = BaseFont.CreateFont(usedFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
iTextSharp.text.Font titleFont = new iTextSharp.text.Font(bf, 40);
iTextSharp.text.Font sentencesFont = new iTextSharp.text.Font(bf, 15);
iTextSharp.text.Font childNamewFont = new iTextSharp.text.Font(bf, 35);
PdfPTable T = new PdfPTable(1);
//Hide the table border
T.DefaultCell.BorderWidth = 0;
T.DefaultCell.HorizontalAlignment = 1;
T.DefaultCell.PaddingTop = 15;
T.DefaultCell.PaddingBottom = 15;
//Set RTL mode
T.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
//Add our text
if (story.Title != null)
{
T.AddCell(new iTextSharp.text.Paragraph(story.Title, titleFont));
}
if (story.Child != null)
{
if (story.Child.FirstName != null && story.Child.LastName != null)
{
T.AddCell(new iTextSharp.text.Phrase(story.Child.FirstName + story.Child.LastName, childNamewFont));
}
}
if (story.Sentences != null)
{
.................
}
document.Add(T);
writer.CloseStream = false;
document.Close();
byte[] bytes = memoryStream.ToArray();
var fileName = path + "\\PDF" + DateTime.Now.ToString("yyyyMMdd-HHMMss") + ".pdf";
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
memoryStream.Position = 0;
memoryStream.Close();
//Send generated pdf as attchment
// Create the file attachment for this email message.
var attachment = Convert.ToBase64String(bytes);
var client = new SendGridClient(Options.SendGridKey);
var msg = new SendGridMessage();
msg.From = new EmailAddress(SD.DefaultEmail, SD.DefaultEmail);
msg.Subject = story.Title;
msg.PlainTextContent = "................";
msg.HtmlContent = "..................";
msg.AddTo(new EmailAddress(recipientEmail));
msg.AddAttachment("Story.pdf", attachment);
try
{
await client.SendEmailAsync(msg);
}
catch (Exception ex)
{
Console.WriteLine("{0} First exception caught.", ex);
}
//Remove form root
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
}
}
catch (FileNotFoundException e)
{
Console.WriteLine($"The file was not found: '{e}'");
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine($"The directory was not found: '{e}'");
}
catch (IOException e)
{
Console.WriteLine($"The file could not be opened: '{e}'");
}
return RedirectToAction("Details", new { id = id });
}
try to edit usedfont variable as bellow :
var usedfont = Path.Combine(webRootPath ,#"\fonts\arial.TTF")
It turns out that the problem is far from iTextSharp. I did a remote debugging from this article.
Two parts of the code was causing the problem.
First, for some reason the folder "dump" was not created on Azure wwwroot folder while locally it is. so, i added these lines:
var webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "dump");
if (!Directory.Exists(path)) //Here
Directory.CreateDirectory(path);
Second, after debugging it shows that creating the file was failing every time. I replaced the following lines:
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
memoryStream.Position = 0;
memoryStream.Close();
With:
using (FileStream fs = new FileStream(fileName, FileMode.Create))
using (var binaryWriter = new BinaryWriter(fs))
{
binaryWriter.Write(bytes, 0, bytes.Length);
binaryWriter.Close();
}
memoryStream.Close();
Hope this post helps someone.

how to reduce the size of multiple images before save to database using asp.net fileuploader

I have done the multiple file up-loader and save the images in database as (byte)
while retrieving those all images memory out of exception was thrown so i want to reduce the size of uploaded multiple files through pragmatically (c#,asp.net)
with that i have problem with reducing the sizes of multiple images using file up-loader in .net before saving to database
protected void DataUploading()
{
try
{
int count;
if (uploader.HasFile)
{
string s = System.IO.Path.GetExtension(uploader.FileName);
if ((s == ".JPG") || (s == ".JPEG") || (s == ".PNG") || (s == ".BMP") || (s == ".jpg") || (s == ".jpeg") || (s == ".png") || (s == ".bmp") || (s == ".jpe"))
{
count = ReferrenceCount();
HttpFileCollection fileCollection = Request.Files;
if (count == 0)
{
count = 0;
}
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
int fileSize = uploadfile.ContentLength;
if (fileSize <= 31457280)//3145728-5242880
{
string fileName = Path.GetFileName(uploadfile.FileName);
if (uploadfile.ContentLength > 0)
{
string contentType = uploader.PostedFile.ContentType;
using (Stream fs = uploadfile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
byte[] newbytes = reducesize(uploadfile);
imagelist.Add(bytes);
refcounts.Add(count);
count += 1;
}
}
}
}
else
{
//image compression code to be written here
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('FILE SIZE SHOULD BE LIMIT TO 5MB')", true);
}
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('ONLY JPEG,BMP,PNG ARE ALLOWED')", true);
}
for (int ij = 0; ij < imagelist.Count; ij++)
{
using (con = new SqlConnection(constr))
{
string query = string.Empty;
query = "INSERT INTO INVENTORY_IMAGES(CLAIM_NUMBER,PHOTOS,REF_NO,UPDATEDATE,MODIFIEDDATE,MODIFIEDBY,CHASSIS) values (#Name, #Data,#REF,#DATE,#datetime,#user,#chassis)";
using (cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", txtclaimnumber.Text);
cmd.Parameters.AddWithValue("#Data", imagelist[ij]);
cmd.Parameters.AddWithValue("#REF", refcounts[ij].ToString());
cmd.Parameters.AddWithValue("#DATE", DateTime.Now.ToString("dd/MM/yyyy"));
cmd.Parameters.AddWithValue("#datetime", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#user", Session["user"].ToString());
cmd.Parameters.AddWithValue("#chassis", txtchasisno.Text);
con.Open();
cmd.ExecuteNonQuery();//'"+DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")+"','"+Session["user"].ToString()+"','"++"'
}
}
}
imagelist.Clear();
refcounts.Clear();
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('PLEASE SELECT A FILE')", true);
}
}
catch (Exception ee)
{
WriteLog(ee.Message);
throw ee;
}
}
private byte[] reducesize(HttpPostedFile HttpPostedFiles)
{
//variable to store the image content
//the size of the variable is initialized to the file content length
byte[] imageBytes = new byte[HttpPostedFiles.ContentLength];
//Gets the underlying System.Web.HttpPostedFile object for a file that is uploaded
//by using the System.Web.UI.WebControls.FileUpload control.
//HttpPostedFile uploadImage = fileUploadS.PostedFile;
//read the image stream from the post and store it in imageBytes
HttpPostedFiles.InputStream.Read(imageBytes, 0, (int)HttpPostedFiles.ContentLength);
//resize image to a thumbnail
MemoryStream thumbnailPhotoStream = ResizeImage(HttpPostedFiles);
byte[] thumbnailImageBytes = thumbnailPhotoStream.ToArray();
return thumbnailImageBytes;
//end
}
private MemoryStream ResizeImage(HttpPostedFile HttpPostedFiless)
{
try
{
Bitmap originalBMP = new Bitmap(HttpPostedFiless.InputStream);
// Create a bitmap with the uploaded file content
//Bitmap originalBMP = new Bitmap(inputContent);
// get the original dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
//calculate the current aspect ratio
int aspectRatio = origWidth / origHeight;
//if the aspect ration is less than 0, default to 1
if (aspectRatio <= 0)
aspectRatio = 1;
//new width of the thumbnail image
int newWidth = 100;
//calculate the height based on the aspect ratio
int newHeight = newWidth / aspectRatio;
// Create a new bitmap to store the new image
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics graphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
graphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
//save the bitmap into a memory stream
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, GetImageFormat(System.IO.Path.GetExtension(HttpPostedFiless.FileName)));
// dispose drawing objects
originalBMP.Dispose();
newBMP.Dispose();
graphics.Dispose();
return stream;
}
catch (Exception ee)
{
WriteLog(ee.Message);
throw;
}
}
private System.Drawing.Imaging.ImageFormat GetImageFormat(string extension)
{
switch (extension.ToLower())
{
case "jpg":
return System.Drawing.Imaging.ImageFormat.Jpeg;
case "bmp":
return System.Drawing.Imaging.ImageFormat.Bmp;
case "png":
return System.Drawing.Imaging.ImageFormat.Png;
}
return System.Drawing.Imaging.ImageFormat.Jpeg;
}

Component One pdf generation using draw image crashing if printing pdf pages more than 40

I'm using below code to generate pdf of a page having listview. And it all works good till I have a very small list once I got list with more than 50 items it crashing with memory exception. I think variable pdf is taking all memory. I have checked using profiling it goes above 180 and pdf variable was on top when I took snapshot at profile.
async PDFTest_Loaded(int a)
{
try
{
pdf = new C1PdfDocument(PaperKind.Letter);
pdf.Compression = CompressionLevel.NoCompression;
WriteableBitmap writeableBmp = await initializeImage();
List<WriteableBitmap> ListBitmaps = new List<WriteableBitmap>();
pdfPage PageBitmaps = new pdfPage();
FrameworkElement header = RTABlock as FrameworkElement;
header.Arrange(pdf.PageRectangle);
var headerImage = await CreateBitmap(header);
FrameworkElement Pageheader = SalikPaymentReceipt as FrameworkElement;
Pageheader.Arrange(pdf.PageRectangle);
var PageHeaderImage = await CreateBitmap(Pageheader);
double pdfImageWidth = 0;
foreach (var item in EpayPreviewListView.Items)
{
List<WriteableBitmap> temp = new List<WriteableBitmap>();
var obj = EpayPreviewListView.ContainerFromItem(item);
List<FrameworkElement> controls = Children(obj);
StackPanel ListItemStackPanel = controls.Where(x => x is StackPanel && x.Name == "ListItemStackPanel").First() as StackPanel;
if (ListItemStackPanel is StackPanel)
{
StackPanel itemui = ListItemStackPanel as StackPanel;
if (!(pdfImageWidth > 0))
{
pdfImageWidth = itemui.ActualWidth;
}
itemui.Arrange(new Rect(0, 0, pdfImageWidth, pdf.PageRectangle.Height));
temp.Add(await CreateBitmap(itemui));
PageBitmaps = new pdfPage() { bitmap = temp };
CreateDocumentText(pdf, headerImage, writeableBmp, PageHeaderImage, PageBitmaps);
PageBitmaps = null;
temp = new List<WriteableBitmap>();
}
}
StorageFile Assets = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("Salik Payment Receipts.pdf", CreationCollisionOption.GenerateUniqueName);
PdfUtils.Save(pdf, Assets);
EpayPreviewListView.InvalidateArrange();
EpayPreviewListView.UpdateLayout();
LoadingProgress.Visibility = Visibility.Collapsed;
PrintButton.IsEnabled = true;
}
catch (Exception ex)
{
Debugger.Break();
}
}
public List<FrameworkElement> Children(DependencyObject parent)
{
try
{
var list = new List<FrameworkElement>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is StackPanel || child is TextBlock || child is ListView)
list.Add(child as FrameworkElement);
list.AddRange(Children(child));
}
return list;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString() + "\n\n" + e.StackTrace);
Debugger.Break();
return null;
}
}
async public Task<WriteableBitmap> CreateBitmap(FrameworkElement element)
{
// render element to image (WinRT)
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(element);
var wb = new WriteableBitmap(renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);
(await renderTargetBitmap.GetPixelsAsync()).CopyTo(wb.PixelBuffer);
//var rect = new Rect(0, 0, renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);
if (!App.IsEnglishSelected)
{
wb = wb.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
}
return wb;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString() + "\n\n" + ex.StackTrace);
Debugger.Break();
return new WriteableBitmap(0, 0);
}
}
bool isFirst = true;
void CreateDocumentText(C1PdfDocument pdf, WriteableBitmap headerImage, WriteableBitmap writeableBmp, WriteableBitmap pageHeading, pdfPage ListItem)
{
try
{
if (!isFirst)
{
pdf.NewPage();
}
isFirst = false;
pdf.Landscape = false;
double contentHeight = 0;
double leftMargin = 0;
string fontName = "Arial";
// measure and show some text
var text = App.GetResource("RoadandTransportAuthority");
var font = new Font(fontName, 36, PdfFontStyle.Bold);
// create StringFormat used to set text alignment and line spacing
var fmt = new StringFormat();
fmt.Alignment = HorizontalAlignment.Center;
var rc = new Rect(0, 0,
pdf.PageRectangle.Width, headerImage.PixelHeight);
pdf.DrawImage(headerImage, rc, ContentAlignment.MiddleCenter, Stretch.None);
contentHeight += headerImage.PixelHeight + 2;
rc = new Rect(0, contentHeight, pdf.PageRectangle.Width, writeableBmp.PixelHeight);
pdf.DrawImage(writeableBmp, rc);
contentHeight += writeableBmp.PixelHeight + 5;
rc = new Rect(leftMargin, contentHeight,
pdf.PageRectangle.Width,
pageHeading.PixelHeight);
pdf.DrawImage(pageHeading, rc, ContentAlignment.MiddleCenter, Stretch.None);
contentHeight += pageHeading.PixelHeight + 2;
Debug.WriteLine(ListItem.bitmap.Count.ToString());
for (int i = 0; i < ListItem.bitmap.Count; i++)
{
rc = PdfUtils.Offset(rc, 0, rc.Height + 10);
rc.Height = ListItem.bitmap.ElementAt(i).PixelHeight;
pdf.DrawImage(ListItem.bitmap.ElementAt(i), rc, ContentAlignment.TopCenter, Stretch.None);
ListItem.bitmap[i] = null;
}
ListItem = null;
}
catch (Exception e)
{
//...
}
}
It is due to memory clash I have to decrease the quality of images to handle it. Also it takes some time to release memory.

Adding JPG to PDF extremely slow

I'm trying to write an Image to PDF using PDFBox. I'm using their sample (as attached). Everything is fine, but writing 3.5MB jpeg (3200*2500px) takes roughly 2 seconds.
Is this normal ? Is there any way how to make it faster (at least 10x) ?
public void createPDFFromImage( String inputFile, String image, String outputFile )
throws IOException, COSVisitorException
{
// the document
PDDocument doc = null;
try
{
doc = PDDocument.load( inputFile );
//we will add the image to the first page.
PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
PDXObjectImage ximage = null;
if( image.toLowerCase().endsWith( ".jpg" ) )
{
ximage = new PDJpeg(doc, new FileInputStream( image ) );
}
else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
{
ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
}
else
{
//BufferedImage awtImage = ImageIO.read( new File( image ) );
//ximage = new PDPixelMap(doc, awtImage);
throw new IOException( "Image type not supported:" + image );
}
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
contentStream.drawImage( ximage, 20, 20 );
contentStream.close();
doc.save( outputFile );
}
finally
{
if( doc != null )
{
doc.close();
}
}
}
If you are willing to use another product itext could go really fast, take a look at http://tutorials.jenkov.com/java-itext/image.html .Personally, I did this test with a +750k jpg image and took 78 ms
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image2.pdf"));
document.open();
long start = System.currentTimeMillis();
String imageUrl = "c:/Users/dummy/notSoBigImage.jpg";
Image image = Image.getInstance((imageUrl));
image.setAbsolutePosition(500f, 650f);
document.add(image);
document.close();
long end = System.currentTimeMillis() - start;
System.out.println("time: " + end + " ms");
} catch(Exception e){
e.printStackTrace();
}