OpenCL imaging - only one pixel is updated - opencl

I'm using Opencl.net and I'm trying to do some image processing on the GPU. Unfortunately only the first pixel ([0;0]) has the correct value, and the rest is (0;0;0;0). The OpenCL kernel should assign 0.5 to all color components of every pixel. It seems to me that the kernel is being executed only once (or perhaps the read function is reading only the first pixel). What am I doing wrong? I've omitted not relevant parts from my code:
...
int intPtrSize = 0;
intPtrSize = Marshal.SizeOf(typeof(IntPtr));
Cl.Mem srcImage2DBuffer;
Cl.ImageFormat imageFormat = new Cl.ImageFormat(Cl.ChannelOrder.ARGB, Cl.ChannelType.Float);
int imgWidth = 0, imgHeight = 0;
IntPtr srcFloatDataPtr;
int srcIMGBytesSize = 0;
GCHandle pinnedSrcFloatArray;
//Load image from file into OpenCL buffer
using (FileStream imageFileStream = new FileStream(inputImagePath, FileMode.Open) ) {
System.Drawing.Image inputImage = System.Drawing.Image.FromStream( imageFileStream );
imgWidth = inputImage.Width;
imgHeight = inputImage.Height;
System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(inputImage);
BitmapData bitmapData = bmpImage.LockBits( new Rectangle(0, 0, bmpImage.Width, bmpImage.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
srcIMGBytesSize = bitmapData.Stride * bitmapData.Height;
//Convert image from byte to float array
byte[] inputByteArray = new byte[srcIMGBytesSize];
Marshal.Copy(bitmapData.Scan0, inputByteArray, 0, srcIMGBytesSize);
bmpImage.UnlockBits( bitmapData );
float[] inputFloatArray = new float[srcIMGBytesSize];
Array.Copy(inputByteArray, inputFloatArray, srcIMGBytesSize);
for (int i = 0; i < srcIMGBytesSize; i++) {
inputFloatArray[i] /= 255.0f;
}
pinnedSrcFloatArray = GCHandle.Alloc(inputFloatArray, GCHandleType.Pinned);
srcFloatDataPtr = pinnedSrcFloatArray.AddrOfPinnedObject();
srcImage2DBuffer = Cl.CreateImage2D(_context, Cl.MemFlags.CopyHostPtr | Cl.MemFlags.ReadOnly, imageFormat,
(IntPtr)bitmapData.Width, (IntPtr)bitmapData.Height,
(IntPtr)0, srcFloatDataPtr, out error);
}
float[] outputFloatArray = new float[srcIMGBytesSize];
//I'm not sure whether the pointer here is correct or not.
Cl.Mem resultImage2DBuffer = Cl.CreateImage2D(_context, Cl.MemFlags.CopyHostPtr | Cl.MemFlags.WriteOnly, imageFormat,
(IntPtr)imgWidth, (IntPtr)imgHeight, (IntPtr)0, outputFloatDataPtr, out error);
error = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, srcImage2DBuffer);
error |= Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, resultImage2DBuffer);
...
IntPtr[] originPtr = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 };
IntPtr[] regionPtr = new IntPtr[] { (IntPtr)1, (IntPtr)1, (IntPtr)1 };
IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)imgWidth, (IntPtr)imgHeight, (IntPtr)1 };
error = Cl.EnqueueWriteImage(cmdQueue, srcImage2DBuffer, Cl.Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, srcFloatDataPtr, 0, null, out clevent);
pinnedSrcFloatArray.Free();
error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent);
error = Cl.EnqueueReadImage(cmdQueue, resultImage2DBuffer, Cl.Bool.True, originPtr, regionPtr,
(IntPtr)0, (IntPtr)0, outputFloatArray, 0, null, out clevent);
for (int i = 0; i < srcIMGBytesSize; i++) {
outputFloatArray[i] *= 255.0f;
}
//Right here I'm learning that all of the components are 0
for (int i = 0; i < srcIMGBytesSize; i+=4) {
Console.WriteLine("(" + outputFloatArray[i] + "; " + outputFloatArray[i+1] + "; "
+ outputFloatArray[i+2] + "; " + outputFloatArray[i+3] + ")");
}
Thank you!

I've figured out the problem. The region in Cl.EnqueueWriteImage/Cl.EnqueueReadImage should be (imageWidth, imageHeight, 1) instead of (1, 1, 1):
IntPtr[] regionPtr = new IntPtr[] { (IntPtr)imgWidth, (IntPtr)imgHeight, (IntPtr)1 };

Related

First page is blackened after adding watermark

Page is blackened after adding watermark in case of some pdf files . Please see attached image.
What could be the reason , and possible fix.
see the blacked out page image
It does not happen for all the files but for some files only.
Code is here in dotnetfiddle.
var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
} var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
}

Multi image upload with EXIF rotation correction

Hope someone can help? I have read a number of SE posts on FileReader, Blobs, Base64 and EXIF and cobbled together something that is just about there. I am having problems understanding the structure of async functions and the order/delay in the process.
The script below loops through an uploaded array from a multi-part form. In the loop I have readAsDataURL to get Base64 String, and then attempting to readAsArrayBuffer to get the EXIF orientation code from the Blob before transforming a canvas.
I am clearly mixing up the async and getting a little lost.
At this stage it displays the images (and correctly orientates the first) but doesn't read the new EXIF orientation and all images are then rotated the same (presumably because the ArrayBuffer is not in sync?). If I upload more images at once there is some duplication which again must be a sync problem....
$(document).on('change', '#files', function(evt){
var files = evt.target.files;
var readerBase64;
var b64 = [];
var ab = [];
var c=0;
for (var i = 0; f = files[i]; i++) {
console.log('LOOP');
var blob = f;
var readerBase64 = new FileReader();
readerBase64.onload = function(evt){
// console.log('BASE 64 ' + evt.target.result);
b64.push(evt.target.result);
var reader = new FileReader();
reader.onloadend = (function(theFile) {
console.log(this);
console.log('READER');
return function(e) {
console.log('RETURN');
ab.push(e.target.result);
console.log(ab[c]);
var view = new DataView(ab[c]);
ori = 1;
if (view.getUint16(0, false) != 0xFFD8){ori = -2};
var length = view.byteLength,
offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) {
ori = -1;
}
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
ori = view.getUint16(offset + (i * 12) + 8, little);
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
console.log('ori '+ori);
// console.log(b64[c]);
base64String = b64[c];
var img = document.createElement('img');
img.setAttribute('src',base64String);
//img.src = e.target.result;
img.onload = function () {
var canvas = document.createElement('canvas');
var MAX_WIDTH =1000;
var MAX_HEIGHT =800;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < ori && ori < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (ori) {
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, width, height ); break;
case 4: ctx.transform(1, 0, 0, -1, 0, height ); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, height , 0); break;
case 7: ctx.transform(0, -1, -1, 0, height , width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
default: break;
}
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/jpg");
//alert(dataurl);
// Render thumbnail.
var span = document.createElement('span');
//var ii = $('#list span').length - 2;
// if(ii > 0){
// span.setAttribute('class','hide');
// $('#list span:nth-child(3) p').text("+"+ii);
// }
span.innerHTML =
[
'<input type="image" class="thumb" name="imgs[]" value="',
dataurl,
'" src="', dataurl,
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
c++;
}
}
})(f);
reader.readAsArrayBuffer(blob.slice(0, 64 * 1024));
}
readerBase64.readAsDataURL(f);
// console.log(f);
}
}); // Files change
I have solved it, but perhaps not very gracefully. The uploaded, resized and orientation corrected images are added to the form in an element named #list ready for posting to the server. Here is the code for anyone else:
$(document).on('change', '#files', function(evt){
var files = evt.target.files;
var f;
for (var i = 0; f = files[i]; i++) {
var blob = f;
getOrientation(f, function(ori , f) {
console.log(f);
var readerBase64 = new FileReader();
readerBase64.onload = function(evt){
console.log(ori);
console.log(evt.target.result);
base64String = evt.target.result;
var img = document.createElement('img');
img.setAttribute('src',base64String);
//img.src = e.target.result;
img.onload = function () {
var canvas = document.createElement('canvas');
var MAX_WIDTH =1000;
var MAX_HEIGHT =800;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < ori && ori < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (ori) {
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, width, height ); break;
case 4: ctx.transform(1, 0, 0, -1, 0, height ); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, height , 0); break;
case 7: ctx.transform(0, -1, -1, 0, height , width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
default: break;
}
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/jpg");
//alert(dataurl);
// Render thumbnail.
var span = document.createElement('span');
//var ii = $('#list span').length - 2;
// if(ii > 0){
// span.setAttribute('class','hide');
// $('#list span:nth-child(3) p').text("+"+ii);
// }
span.innerHTML =
[
'<input type="image" class="thumb" name="imgs[]" value="',
dataurl,
'" src="', dataurl,
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
}
};
readerBase64.readAsDataURL(f);
});
}
});
Using the function I found on here with a minor change to send the file Blob back with the orientation in the callback:
//from http://stackoverflow.com/a/32490603
function getOrientation(file, callback) {
var reader = new FileReader();
reader.onload = function(event) {
var view = new DataView(event.target.result);
if (view.getUint16(0, false) != 0xFFD8) return callback(-2, file);
var length = view.byteLength,
offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) {
return callback(-1 , file);
}
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return callback(view.getUint16(offset + (i * 12) + 8, little) , file);
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return callback(-1 , file);
};
reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
};
The solution for the upload was to intercept the post and use AJAX and JQuery to build the POST data from the input[type='image']
$(document).on('submit',function(e){
e.preventDefault();
var data = $('#formFeed').serializeArray();
var msg = $('textarea').val();
data.push({name: 'msg', value: msg});
var y;
$('input[type="image"]').each(function(i, obj) {
y = $(this).attr('src');
data.push({name: 'img', value: y});
});
$.ajax({
cache: false,
type : 'POST',
url : 'http://localhost:3001/newFeed',
data: data,
contentType: "application/x-www-form-urlencoded",
success : function(data) {
console.log(data);
}
});
});

while export to pdf using itexsharp it shows blank page

i made one desktop application using asp.net which convert html to PDF.
basically this application used for generate users PDF from database.
process: first of all i am converting all data to html and then convert to PDF using itextsharp but after generating some PDFs it shows blank pages
any idea or anyone face this type of issue
public static void converttopdf(string HtmlStream, List<Tuple<string, string>> tifffiles, List<Tuple<string, string>> pdffilestomerge, string filename, string patientfirstpagestr, string TableofContent, string patientheader, SqlConnection con, string sectiondetails)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(HtmlStream);
Document document = new Document(PageSize.A4, 30, 30, 42, 44);
string filetogenerate = string.Empty;
if (pdffilestomerge != null && pdffilestomerge.Count > 1)
{
filetogenerate = temppath + filename + "_Temp1.pdf";
}
else
{
filetogenerate = temppath + filename + "_Temp.pdf";
}
PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(filetogenerate, System.IO.FileMode.Create));
HTMLWorker worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();
string[] separator = new string[] { #"<br clear='all' style='page-break-before:always'>" };
string[] pages = HtmlStream.Split(separator, StringSplitOptions.None);
foreach (string page in pages)
{
document.NewPage();
System.Collections.ArrayList htmlarraylist = HTMLWorker.ParseToList(new StringReader(page), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
}
using (var ms = new MemoryStream())
{
if (tifffiles != null)
{
int docid = 0;
foreach (var obj in tifffiles)
{
string filepath = obj.Item2.ToString();
WriteLogEntry("bitmap file path : " + filepath);
if (filepath != string.Empty)
{
try
{
Bitmap myBitmap = new Bitmap(filepath);
System.Drawing.Color pixelColor = myBitmap.GetPixel(50, 50);
if (pixelColor.Name == "ff808080")
{
WriteLogEntry("convert image by irfanview :" + filepath);
LaunchCommandLineApp(filepath, temppath + "Test.jpg");
document.NewPage();
var imgStream = GetImageStream(temppath + "Test.jpg");
var image = iTextSharp.text.Image.GetInstance(imgStream);
image.SetAbsolutePosition(10, 80);
image.ScaleToFit(document.PageSize.Width - 60, document.PageSize.Height - 80);
//image.ScaleToFit(document.PageSize.Width - 30, document.PageSize.Height);
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
document.Add(image);
File.Delete(temppath + "Test.jpg");
}
else
{
document.NewPage();
var imgStream = GetImageStream(filepath);
var image = iTextSharp.text.Image.GetInstance(imgStream);
image.SetAbsolutePosition(10, 80);
image.ScaleToFit(document.PageSize.Width - 60, document.PageSize.Height - 80);
//image.ScaleToFit(document.PageSize.Width - 30, document.PageSize.Height);
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
document.Add(image);
WriteLogEntry("Image added successfully" + filepath);
}
}
catch
{
document.NewPage();
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
WriteLogEntry("Image not valid" + filepath);
}
docid = Convert.ToInt32(obj.Item1);
}
}
}
}
worker.EndDocument();
worker.Close();
document.Close();
if (pdffilestomerge != null && pdffilestomerge.Count > 1)
{
string file = temppath + filename + "_Temp.pdf";
mergepdf(file, pdffilestomerge, filetogenerate);
}
PdfReader pdfreader = new PdfReader(temppath + filename + "_Temp.pdf");
Document document1 = new Document(PageSize.A4, 30, 30, 42, 44);
PdfWriter writer1 = PdfWriter.GetInstance(document1, new FileStream(FinalOutputPath + filename + ".pdf", FileMode.Create));
//HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
//footer.Alignment = Element.ALIGN_RIGHT;
//footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
//document1.Footer = footer;
//HeaderFooter header = new HeaderFooter(new Phrase(""), true);
//header.Alignment = Element.ALIGN_LEFT;
//header.Border = iTextSharp.text.Rectangle.NO_BORDER;
//document1.Add(header);
document1.Open();
PdfContentByte cb1 = writer1.DirectContent;
PdfImportedPage page1;
string test1 = TableofContent; int TableofContentPageCount = 0; int SectionPageStartNumber = 0;
string lastdocnamestr = "";
for (int t = 1; t <= pdfreader.NumberOfPages; t++)
{
document1.NewPage();
HeaderFooter header = new HeaderFooter(new Phrase(""), true);
header.Alignment = Element.ALIGN_LEFT;
header.Border = iTextSharp.text.Rectangle.NO_BORDER;
HeaderFooter header1 = new HeaderFooter(new Phrase(" "), true);
header1.Alignment = Element.ALIGN_LEFT;
header1.Border = iTextSharp.text.Rectangle.NO_BORDER;
HeaderFooter header2 = new HeaderFooter(new Phrase(" "), true);
header2.Alignment = Element.ALIGN_LEFT;
header2.Border = iTextSharp.text.Rectangle.NO_BORDER;
document1.Add(header);
document1.Add(header1);
document1.Add(header2);
page1 = writer1.GetImportedPage(pdfreader, t);
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
byte[] pdfcontent = pdfreader.GetPageContent(t);
//PdfDictionary dict = pdfreader.GetPageN(t);
string contentStream = System.Text.Encoding.Default.GetString(pdfcontent);
var contentByte = writer1.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 8);
var multiLineString = "";
var multiLineString1 = "";
string test = getBetween(contentStream, "#~#", "#~#");
if (test.Length > 0)
{
test1 = test1.Replace(test + ".", t.ToString());
DataTable dt = getdocdetailforheader(Convert.ToInt32(test.Replace("DID", "")), con);
if (dt.Rows.Count > 0)
{
multiLineString = dt.Rows[0]["DocumentName"].ToString() + " - " + Convert.ToDateTime(dt.Rows[0]["EncounterDTTM"].ToString()).ToString("MM/dd/yyyy") + " | Owner : " + dt.Rows[0]["Ownername"].ToString();
lastdocnamestr = multiLineString;
WriteLogEntry(multiLineString);
}
if (TableofContentPageCount == 0)
{
TableofContentPageCount = t;
}
}
//if (contentStream.Contains("sectionstart") && SectionPageStartNumber == 0) SectionPageStartNumber = t;
if (lastdocnamestr != string.Empty)
{
multiLineString = lastdocnamestr;
}
//else
//{
// if (TableofContentPageCount == 0)
// {
// multiLineString = "Table of Content";
// }
//}
multiLineString1 = patientheader;
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString, 15, 820, 0);
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString1, 15, 810, 0);
contentByte.EndText();
string relLogo = Directory.GetCurrentDirectory().ToString().Replace("bin", "").Replace("Debug", "").Replace("\\\\", "") + "\\Image\\MFA_LOGO.png";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(relLogo);
jpg.ScaleAbsolute(38f, 38f);
jpg.SetAbsolutePosition(document1.PageSize.Width - 70, 806);
jpg.Alignment = Element.ALIGN_RIGHT;
document1.Add(jpg);
cb1.MoveTo(0, 805);
cb1.LineTo(document1.PageSize.Width, 805);
cb1.Stroke();
cb1.AddTemplate(page1, 0, 0);
}
SectionPageStartNumber = pdfreader.NumberOfPages + 1;
System.Collections.ArrayList htmlarraylist1 = HTMLWorker.ParseToList(new StringReader(sectiondetails), null);
document1.NewPage();
for (int k = 0; k < htmlarraylist1.Count; k++)
{
document1.Add((IElement)htmlarraylist1[k]);
}
document1.Close();
FinalPDF(FinalOutputPath + filename + ".pdf", FinalOutputPath + filename + "_1.pdf", patientfirstpagestr, test1, TableofContentPageCount, patientheader, SectionPageStartNumber);
File.Delete(temppath + filename + "_Temp.pdf");

The OnEndPage event and a table with a RowSpan

I added the creation of a table cone page header in OnEndPage. In table I a RowSpan that is not printed, while the rest is.
table.WriteSelectedRows (0, -1, pageSize.GetLeft (25), pageSize.GetTop (10), cb);
If I remove the RowSpan prints!
This is the code I use:
public override void OnEndPage(PdfWriter writer, Document document)
{
if (document.PageNumber != 1)
{
if (report.repeatHead) //ripete l'intestazione del report su tutte le pagine di stampa
{
repeatHead(writer, document);
}
else
{
if (document.PageNumber == 2) //ripete l'intestazione del report solo sulla second pagina dopo la copertina
{
repeatHead(writer, document);
}
}
}
}
public void repeatHead(PdfWriter writer, Document document)
{
//OnStartPage
base.OnStartPage(writer, document);
Rectangle pageSize = document.PageSize;
PdfPTable table = new PdfPTable(2);
//table.WidthPercentage = 100;
table.TotalWidth = pageSize.Width - 50;
table.DefaultCell.Border = Rectangle.NO_BORDER;
//impostazione larghezza celle
iTextSharp.text.Rectangle rect = PageSize.A4;
float pageWidth = rect.Width;
table.SetWidthPercentage(new float[]
{
(float).70 * pageWidth ,
(float).30 * pageWidth,
}, rect);
//Cella nome banca
table.AddCell(CellTest(report.banca, 1, 2));
//Cella descrizione indagine
table.AddCell(CellTest("Valore1", 0, 0));
//Cella data apertura
table.AddCell(CellTest("Data apertura: " + DateTime.Now, 0, 0));
//Cella descrizione
table.AddCell(CellTest("Descrizione", 0, 0));
//Cella data chiusura
table.AddCell(CellTest("Data chiusura: " + DateTime.Now, 0, 0));
table.WriteSelectedRows(0, -1, pageSize.GetLeft(25), pageSize.GetTop(10), cb);
}
private PdfPCell CellTest(string value, int colSpan, int rowSpan)
{
iTextSharp.text.Font font = FontFactory.GetFont("Arial");
PdfPCell c = new PdfPCell(new Phrase(value, font));
c.BorderWidthLeft = 1f;
c.BorderWidthTop = 1f;
c.BorderWidthRight = 1f;
c.BorderWidthBottom = 1f;
if (rowSpan != 0) { c.Rowspan = rowSpan; }
if (colSpan != 0) { c.Colspan = colSpan; }
return c;
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
template.BeginText();
template.SetFontAndSize(bf, 8);
template.SetTextMatrix(0, 0);
template.ShowText("" + (writer.PageNumber - 1));
template.EndText();
}

datatype image in $.ajax

in page cap.aspx
==========================================================================
string code = GetRandomText();
Bitmap bitmap = new Bitmap(160,50,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
Pen pen = new Pen(Color.LavenderBlush);
Rectangle rect = new Rectangle(0,0,160,50);
SolidBrush b = new SolidBrush(Color.LightPink);
SolidBrush blue = new SolidBrush(Color.White);
int counter = 0;
g.DrawRectangle(pen, rect);
g.FillRectangle(b, rect);
for (int i = 0; i < code.Length; i++)
{
g.DrawString(code[i].ToString(), new Font("Tahoma", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
counter += 20;
}
DrawRandomLines(g);
bitmap.Save(Response.OutputStream,ImageFormat.Gif);
g.Dispose();
b.Dispose();
blue.Dispose();
bitmap.Dispose();
===================================================================================
<div id="DIVdialog" style="display:none">
<img src="cap.aspx"/>
</div>
===================================================================================
$("#DIVdialog").dialog();
==================================================================================
show dialog but does not show image? address cap.aspx is correct!
how get cap.aspx by $.ajax and datatype:image?
I think that the key here is to add the ContentType and the BufferOutput
context.Response.ContentType = "image/gif";
context.Response.BufferOutput = false;
Eg:
public void RenderIt(HttpContext context)
{
context.Response.ContentType = "image/gif";
context.Response.BufferOutput = false;
string code = GetRandomText();
using(Bitmap bitmap = new Bitmap(160,50,System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using(Graphics g = Graphics.FromImage(bitmap))
{
using(Pen pen = new Pen(Color.LavenderBlush)
{
using(SolidBrush b = new SolidBrush(Color.LightPink))
{
using(SolidBrush blue = new SolidBrush(Color.White))
{
Rectangle rect = new Rectangle(0,0,160,50);
int counter = 0;
g.DrawRectangle(pen, rect);
g.FillRectangle(b, rect);
for (int i = 0; i < code.Length; i++)
{
g.DrawString(code[i].ToString(), new Font("Tahoma", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
counter += 20;
}
DrawRandomLines(g);
g.Dispose();
b.Dispose();
blue.Dispose();
// Return
bitmap.Save(context.Response.OutputStream, ImageFormat.Gif);
// Dispose
bitmap.Dispose();
}
}
}
}
}
context.Response.End();
}

Resources