PDFStamper not working for newer versions of iTextSharp - c#

The latest version of iTextSharp is 5.5.11.
When I run the exact same code against 5.5.0 it works.
It's a pretty simple request - use iTextSharp to set a watermark on an existing PDF in-memory.
Here's the offending code:
private static Stream Watermark(Stream inStream, WatermarkRequest request)
{
using (var outStream = new MemoryStream((int)(inStream.Length + 4096)))
{
using (var reader = new PdfReader(inStream))
using (var stamper = new PdfStamper(reader, outStream))
{
var opacity = request.Opacity.HasValue ? request.Opacity.Value : 0.75f;
var angle = request.Angle.HasValue ? request.Angle.Value : 45;
var size = request.Size.HasValue ? request.Size.Value : 72f;
var color = new BaseColor(1f, 0f, 0f, 0f);
if (!String.IsNullOrEmpty(request.Color))
{
var rgba = PDF.Lib.RGBA.convert(request.Color);
color = new BaseColor((float)rgba.R, (float)rgba.G, (float)rgba.B, 0f);
}
for (var n = 1; n <= reader.NumberOfPages; n++)
{
var pcb = stamper.GetOverContent(n);
var gstate = new PdfGState() { FillOpacity = opacity, StrokeOpacity = opacity };
pcb.SaveState();
pcb.SetGState(gstate);
pcb.SetColorFill(color);
pcb.BeginText();
pcb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, Encoding.Default.WebName, true), size);
var ps = reader.GetPageSize(n);
var x = (ps.Right + ps.Left) / 2;
var y = (ps.Bottom + ps.Top) / 2;
pcb.ShowTextAligned(Element.ALIGN_CENTER, request.Text, x, y, angle);
pcb.EndText();
pcb.RestoreState();
}
}
return new MemoryStream(outStream.ToArray());
}
}

Related

Image stitching with opencvsharp

I want to make image stitching with openCvSharp but something goes wrong. Since I do not get the right output of 2 image stitched together.
I was fallowing the tutorial in python link and converting it in to C# code.
Here are 2 photo examples
The output where image should be stitched I get wrong result. It looks the same as image 2.
I gues something goes wrong in line, or somewhere after the line
Cv2.WarpPerspective(trainImg, result, H, new OpenCvSharp.Size(width, height));
Here is the full code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bool debugImages = true;
string locationFolder = "";
OpenFileDialog dlg = new OpenFileDialog();
dlg.CheckFileExists = true;
dlg.Multiselect = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
locationFolder = Path.GetDirectoryName(dlg.FileNames[0]) + "\\output\\";
List<Mat> imagesMat = new List<Mat>();
for (var i = 0; i < dlg.FileNames.Length; i++)
{
using (Bitmap fromFile = new Bitmap(dlg.FileNames[i]))
{
Mat source = BitmapConverter.ToMat(fromFile);
imagesMat.Add(source);
}
}
if (imagesMat.Count != 2)
throw new Exception("Select only 2 images!!!");
int imageCounter = 0;
Mat trainImg = imagesMat[0];
Mat queryImg = imagesMat[1];
Mat trainImg_gray = new Mat();
Mat queryImg_gray = new Mat();
Cv2.CvtColor(trainImg, trainImg_gray, ColorConversionCodes.BGRA2GRAY);
Cv2.CvtColor(queryImg, queryImg_gray, ColorConversionCodes.BGRA2GRAY);
// detecting keypoints
// FastFeatureDetector, StarDetector, SIFT, SURF, ORB, BRISK, MSER, GFTTDetector, DenseFeatureDetector, SimpleBlobDetector
string method = "SURF";
string feature_matching = "bf"; //bf, knn
var descriptor = SURF.Create(500, 4, 2, true);
Mat descriptors1 = new Mat();
Mat descriptors2 = new Mat();
KeyPoint[] kpsA;
KeyPoint[] kpsB;
descriptor.DetectAndCompute(trainImg_gray, null, out kpsA, descriptors1);
descriptor.DetectAndCompute(queryImg_gray, null, out kpsB, descriptors2);
// Match descriptor vectors
//var flannMatcher = new FlannBasedMatcher();
DMatch[] matches;
if (feature_matching == "bf")
matches = matchKeyPointsBF(descriptors1, descriptors2, method);
else
matches = matchKeyPointsKNN(descriptors1, descriptors2, 0.75, method);
var bfView = new Mat();
Cv2.DrawMatches(trainImg, kpsA, queryImg, kpsB, matches, bfView, null, flags: DrawMatchesFlags.NotDrawSinglePoints);
if (debugImages)
{
using (Bitmap resultBitmap = BitmapConverter.ToBitmap(bfView))
resultBitmap.Save(locationFolder + (imageCounter++).ToString().PadLeft(3, '0') + ".png", ImageFormat.Png); //1
}
Mat H = getHomography(kpsA, kpsB, descriptors1, descriptors2, matches, 4);
if (H == null)
throw new Exception("No Homography!!!");
//for (var i = 0; i < H.Cols; i++)
//{
// for (var j = 0; j < H.Rows; j++)
// Console.Write(H.At<float>(i, j) + " ");
// Console.WriteLine("");
//}
double width = trainImg.Size().Width + queryImg.Size().Width;
double height = trainImg.Size().Height + queryImg.Size().Height;
Mat result = new Mat();
Cv2.WarpPerspective(trainImg, result, H, new OpenCvSharp.Size(width, height));
if (debugImages)
{
using (Bitmap resultBitmap = BitmapConverter.ToBitmap(result))
resultBitmap.Save(locationFolder + (imageCounter++).ToString().PadLeft(3, '0') + ".png", ImageFormat.Png); //1
}
result[new Rect(new OpenCvSharp.Point(0, 0), new OpenCvSharp.Size(queryImg.Size().Width, queryImg.Size().Height))] = queryImg;
if (debugImages)
{
using (Bitmap resultBitmap = BitmapConverter.ToBitmap(result))
resultBitmap.Save(locationFolder + (imageCounter++).ToString().PadLeft(3, '0') + ".png", ImageFormat.Png); //2
}
//# transform the panorama image to grayscale and threshold it
Mat gray = result.Clone();
Cv2.CvtColor(result, gray, ColorConversionCodes.BGR2GRAY);
Mat thresh = new Mat();
double thresh2 = Cv2.Threshold(gray, thresh, 0, 255, ThresholdTypes.Binary);
//# Finds contours from the binary image
OpenCvSharp.Point[][] cnts;
HierarchyIndex[] hierarchy;
Cv2.FindContours(thresh, out cnts, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
OpenCvSharp.Point[] cnts2 = new OpenCvSharp.Point[cnts[0].Length];
for (var k = 0; k < cnts[0].Length; k++)
cnts2[k] = cnts[0][k];
//InputArray ptsA = InputArray.Create(cnts2);
//var c = Cv2.ContourArea(ptsA, true);
OpenCvSharp.Rect xywh = Cv2.BoundingRect(cnts2);
result = result[new Rect(new OpenCvSharp.Point(xywh.X, xywh.Y), new OpenCvSharp.Size(xywh.Width, xywh.Height))];
//result = result[new Rect(new OpenCvSharp.Point(0, 0), new OpenCvSharp.Size(256, 256))];
Bitmap endResultBitmap = BitmapConverter.ToBitmap(result);
endResultBitmap.Save(locationFolder + (imageCounter++).ToString().PadLeft(3, '0') + ".png", ImageFormat.Png); //4
Environment.Exit(-1);
}
}
private BFMatcher createMatcher(string method, bool crossCheck)
{
//"Create and return a Matcher Object"
if (method == "SURF" || method == "SIFT")
return new BFMatcher(NormTypes.L2, crossCheck);
else //if (method == "ORB" || method == "BRISK")
return new BFMatcher(NormTypes.Hamming, crossCheck);
}
private DMatch[] matchKeyPointsBF(Mat featuresA, Mat featuresB, string method)
{
BFMatcher bf = createMatcher(method, crossCheck: true);
// # Match descriptors.
DMatch[] bfMatches = bf.Match(featuresA, featuresB);
//# Sort the features in order of distance.
//# The points with small distance (more similarity) are ordered first in the vector
DMatch[] rawMatches = bfMatches.OrderBy(a => a.Distance).ToArray();
if (rawMatches.Length > 100)
Array.Resize(ref rawMatches, 100);
return rawMatches;
}
private DMatch[] matchKeyPointsKNN(Mat featuresA, Mat featuresB, double ratio, string method)
{
BFMatcher bf = createMatcher(method, crossCheck: false);
// # compute the raw matches and initialize the list of actual matches
DMatch[][] rawMatches = bf.KnnMatch(featuresA, featuresB, 2);
List<DMatch> rawMatches2 = new List<DMatch>();
//# loop over the raw matches
DMatch prevmatchN = rawMatches[0][0];
rawMatches2.Add(prevmatchN);
for (int m = 0; m < rawMatches.Length; m++)
{
for (int n = 0; n < rawMatches[m].Length; n++)
{
//# ensure the distance is within a certain ratio of each
//# other (i.e. Lowe's ratio test)
DMatch matchN = rawMatches[m][n];
if (n == 0)
prevmatchN = matchN;
if (prevmatchN.Distance < matchN.Distance * (ratio))
rawMatches2.Add(matchN);
if (rawMatches2.Count >= 100)
break;
}
}
return rawMatches2.ToArray();
}
private Mat getHomography(KeyPoint[] kpsA, KeyPoint[] kpsB, Mat featuresA, Mat featuresB, DMatch[] matches, int reprojThresh)
{
//# convert the keypoints to numpy arrays
Point2f[] PtA = new Point2f[matches.Length];
Point2f[] PtB = new Point2f[matches.Length];
for (int i = 0; i < matches.Length; i++)
{
KeyPoint kpsAI = kpsA[matches[i].QueryIdx];
KeyPoint kpsBI = kpsB[matches[i].TrainIdx];
PtA[i] = new Point2f(kpsAI.Pt.X, kpsAI.Pt.Y);
PtB[i] = new Point2f(kpsBI.Pt.X, kpsBI.Pt.Y);
}
InputArray ptsA = InputArray.Create(PtA);
InputArray ptsB = InputArray.Create(PtB);
if (matches.Length > 4)
{
//You get the homography matrix usin
Mat H = Cv2.FindHomography(ptsA, ptsB, HomographyMethods.Ransac, reprojThresh);
//and then to get any point on the target picture from the original picture:
//Mat targetPoint = new Mat();
//Cv2.PerspectiveTransform(ptsA, targetPoint, H);
return H;
}
else
return null;
}
}

iTextSharp in MVC, how to add image on 3rd page of pdf with custom x,y margins?

I am creating a PDF in MVC project using iTextSharp on .NET platform. I am sending a HTML div in "Download PDF" function and adding image from c# code using iTextSharp classes, but now I want to add an Image on 3rd page but unfortunately I am unable to do that. Please help me.
Please find the below code that I wrote for adding image on first page, last page and a loop for adding image on each page... (BUT I CAN NOT ADD AN IMAGE ONLY ON 3RD PAGE)...
using (MemoryStream stream = new System.IO.MemoryStream())
{
string Grid = GridHtml.Replace("<br>", "\n\r");
StringReader sr = new StringReader(Grid);
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 100f, 0f);
pdfDoc.SetMargins(50f, 50f, 90f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
MyEvent events = new MyEvent();
writer.PageEvent = events;
pdfDoc.Open();
string imageURL1 = Server.MapPath("~/UploadedFiles/Calibehr.png");
iTextSharp.text.Image jpg12 = iTextSharp.text.Image.GetInstance(imageURL1);
////Resize image depend upon your need
jpg12.ScaleToFit(140f, 120f);
jpg12.SpacingBefore = 10f;
//////Give some space after the image
jpg12.SpacingAfter = 1f;
jpg12.Alignment = Element.ALIGN_CENTER;
jpg12.SetAbsolutePosition(40, 750);
pdfDoc.Add(jpg12);
if ((fc["hdnFormatType"] != "ManageService"))
{
string imageURL3 = Server.MapPath("~/UploadedFiles/Swati-Sign.png");
iTextSharp.text.Image jpgSign = iTextSharp.text.Image.GetInstance(imageURL3);
////Resize image depend upon your need
jpgSign.ScaleToFit(140f, 120f);
jpgSign.SpacingBefore = 10f;
//////Give some space after the image
jpgSign.SpacingAfter = 1f;
jpgSign.Alignment = Element.ALIGN_LEFT;
jpgSign.SetAbsolutePosition(40, 160);
//jpg12.
pdfDoc.Add(jpgSign);
}
string imageURL2 = Server.MapPath("~/UploadedFiles/footer.jpg");
iTextSharp.text.Image jpgFooter = iTextSharp.text.Image.GetInstance(imageURL2);
////Resize image depend upon your need
jpgFooter.ScaleToFit(140f, 120f);
jpgFooter.SpacingBefore = 10f;
//////Give some space after the image
jpgFooter.SpacingAfter = 1f;
jpgFooter.Alignment = Element.ALIGN_LEFT;
jpgFooter.ScaleAbsoluteWidth(510);
jpgFooter.ScaleAbsoluteHeight(70);
jpgFooter.SetAbsolutePosition(40, 0);
//jpg12.
pdfDoc.Add(jpgFooter);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
string imageURL4 = Server.MapPath("~/UploadedFiles/Swati-Sign.png");
iTextSharp.text.Image jpgFooterSign = iTextSharp.text.Image.GetInstance(imageURL4);
////Resize image depend upon your need
jpgFooterSign.ScaleToFit(140f, 120f);
jpgFooterSign.SpacingBefore = 10f;
//////Give some space after the image
jpgFooterSign.SpacingAfter = 1f;
jpgFooterSign.Alignment = Element.ALIGN_LEFT;
if ((fc["hdnFormatType"] == "ManageService"))
{
jpgFooterSign.SetAbsolutePosition(20, 150);
}
else
{
jpgFooterSign.SetAbsolutePosition(20, 450);
}
writer.DirectContent.AddImage(jpgFooterSign, false);
pdfDoc.Close();
return File(stream.ToArray(), "application/pdf", CandName + "-" + empId + ".pdf");
}
}
Try this one:- set positions also what you want.
public void AddImage(int pageNumber)
{
if (pageNumber > 0)
{
string pdfTemplate =
#"D:\Input.pdf";
string newFile = #"D:\Output.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
string chartLoc = string.Empty;
chartLoc = #"C:\img.png";
iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(chartLoc);
iTextSharp.text.pdf.PdfContentByte underContent;
iTextSharp.text.Rectangle rect;
try
{
Single X, Y; int pageCount = 0;
rect = pdfReader.GetPageSizeWithRotation(1);
if (chartImg.Width > rect.Width || chartImg.Height > rect.Height)
{
chartImg.ScaleToFit(rect.Width, rect.Height);
X = (rect.Width - chartImg.ScaledWidth) / 2;
Y = (rect.Height - chartImg.ScaledHeight) / 2;
}
else
{
X = (rect.Width - chartImg.Width) / 2;
Y = (rect.Height - chartImg.Height) / 2;
}
chartImg.SetAbsolutePosition(X, Y);
pageCount = pdfReader.NumberOfPages;
//Below to add image to all pages
//for (int i = 1; i < pageCount; i++)
//{
// underContent = pdfStamper.GetOverContent(i);//.GetUnderContent(i);
// underContent.AddImage(chartImg);
//}
if (pageCount >= pageNumber)
{
underContent = pdfStamper.GetOverContent(pageNumber);//.GetUnderContent(i);
underContent.AddImage(chartImg);
}
pdfStamper.Close();
pdfReader.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}

How to get stats from ConnectedComponentsWithStats in EmguCv

I'm working on pedestrians detection algorithm and got stuck on using ConnectedComponentsWithStats() method. I can't get to the values of stats. Here is what I wrote so far:
var labels = new Mat();
var stats = new Mat();
var centroids = new Mat();
var nLabels = CvInvoke.ConnectedComponentsWithStats(greyImage, labels, stats, centroids);
var centroidPoints = new MCvPoint2D64f[nLabels];
centroids.CopyTo(centroidPoints);
foreach (MCvPoint2D64f point in centroidPoints)
{
var x = point.X;
var y = point.Y;
}
The stats are stored as int32's in opencv c++ and have 5 fields x,y,width,height and area.
You can see the opencv implementation of ConnectedComponentsWithStats here.
Also you can see the struct CCStatsOp opencv returns the stats as here.
Sadly EMGUCV has not created the data structure CCStatsOp so you will need to just store the raw integer data like such.
int[] statsData = new int[stats.Rows * stats.Cols];
stats.CopyTo(statsData);
for (int i = 0; i < stats.Rows; i++)
{
var x = statsData[i * stats.Cols + 0];
var y = statsData[i * stats.Cols + 1];
var width = statsData[i * stats.Cols + 2];
var height = statsData[i * stats.Cols + 3];
var area = statsData[i * stats.Cols + 4];
}
You can also roll your own CCStats op with this code here.
Struct
public struct CCStatsOp
{
public Rectangle Rectangle;
public int Area;
}
Code
var labels = new Mat();
var stats = new Mat();
var centroids = new Mat();
var nLabels = CvInvoke.ConnectedComponentsWithStats(greyImage, labels, stats, centroids);
var centroidPoints = new MCvPoint2D64f[nLabels];
centroids.CopyTo(centroidPoints);
CCStatsOp[] statsOp = new CCStatsOp[stats.Rows];
stats.CopyTo(statsOp);
foreach (var statop in statsOp)
{
Console.WriteLine($"Rectangle: {statop.Rectangle} Area: {statop.Area}");
}

How to insert picture into excel using MemoryStream?

Below are two methods, one uses MemoryStream and the other uses real file on the disk.
public void InsertImage(long x, long y, long? width, long? height, string sImagePath, WorksheetPart wsp)
{
try
{
DrawingsPart dp;
ImagePart imgp;
WorksheetDrawing wsd;
ImagePartType ipt;
switch (sImagePath.Substring(sImagePath.LastIndexOf('.') + 1).ToLower())
{
case "png":
ipt = ImagePartType.Png;
break;
case "jpg":
case "jpeg":
ipt = ImagePartType.Jpeg;
break;
case "gif":
ipt = ImagePartType.Gif;
break;
default:
return;
}
if (wsp.DrawingsPart == null)
{
//----- no drawing part exists, add a new one
dp = wsp.AddNewPart<DrawingsPart>();
imgp = dp.AddImagePart(ipt, wsp.GetIdOfPart(dp));
wsd = new WorksheetDrawing();
}
else
{
//----- use existing drawing part
dp = wsp.DrawingsPart;
imgp = dp.AddImagePart(ipt);
dp.CreateRelationshipToPart(imgp);
wsd = dp.WorksheetDrawing;
}
using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
{
imgp.FeedData(fs);
}
int imageNumber = dp.ImageParts.Count<ImagePart>();
if (imageNumber == 1)
{
Drawing drawing = new Drawing();
drawing.Id = dp.GetIdOfPart(imgp);
wsp.Worksheet.Append(drawing);
}
NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
nvdp.Id = new UInt32Value((uint)(1024 + imageNumber));
nvdp.Name = "Picture " + imageNumber.ToString();
nvdp.Description = "";
DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
picLocks.NoChangeAspect = true;
picLocks.NoChangeArrowheads = true;
NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
nvpdp.PictureLocks = picLocks;
NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
nvpp.NonVisualDrawingProperties = nvdp;
nvpp.NonVisualPictureDrawingProperties = nvpdp;
DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();
BlipFill blipFill = new BlipFill();
DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
blip.Embed = dp.GetIdOfPart(imgp);
blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
blipFill.Blip = blip;
blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
blipFill.Append(stretch);
DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
offset.X = 0;
offset.Y = 0;
t2d.Offset = offset;
Bitmap bm = new Bitmap(sImagePath);
DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
if (width == null)
extents.Cx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
else
extents.Cx = width * (long)((float)914400 / bm.HorizontalResolution);
if (height == null)
extents.Cy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
else
extents.Cy = height * (long)((float)914400 / bm.VerticalResolution);
bm.Dispose();
t2d.Extents = extents;
ShapeProperties sp = new ShapeProperties();
sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
sp.Transform2D = t2d;
DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
sp.Append(prstGeom);
sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());
DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
picture.NonVisualPictureProperties = nvpp;
picture.BlipFill = blipFill;
picture.ShapeProperties = sp;
Position pos = new Position();
pos.X = x * 914400 / 72;
pos.Y = y * 914400 / 72;
Extent ext = new Extent();
ext.Cx = extents.Cx;
ext.Cy = extents.Cy;
AbsoluteAnchor anchor = new AbsoluteAnchor();
anchor.Position = pos;
anchor.Extent = ext;
anchor.Append(picture);
anchor.Append(new ClientData());
wsd.Append(anchor);
wsd.Save(dp);
}
catch (Exception ex)
{
throw ex; // or do something more interesting if you want
}
}
//use memorystream
public void InsertImage(long x, long y, long? width, long? height, MemoryStream ms, WorksheetPart wsp)
{
try
{
DrawingsPart dp;
ImagePart imgp;
WorksheetDrawing wsd;
ImagePartType ipt = ImagePartType.Jpeg;
if (wsp.DrawingsPart == null)
{
//----- no drawing part exists, add a new one
dp = wsp.AddNewPart<DrawingsPart>();
imgp = dp.AddImagePart(ipt, wsp.GetIdOfPart(dp));
wsd = new WorksheetDrawing();
}
else
{
//----- use existing drawing part
dp = wsp.DrawingsPart;
imgp = dp.AddImagePart(ipt);
dp.CreateRelationshipToPart(imgp);
wsd = dp.WorksheetDrawing;
}
Bitmap bitmap = new Bitmap(ms);
imgp.FeedData(ms);
int imageNumber = dp.ImageParts.Count<ImagePart>();
if (imageNumber == 1)
{
Drawing drawing = new Drawing();
drawing.Id = dp.GetIdOfPart(imgp);
wsp.Worksheet.Append(drawing);
}
NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
nvdp.Id = new UInt32Value((uint)(1024 + imageNumber));
nvdp.Name = "Picture " + imageNumber.ToString();
nvdp.Description = "";
DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
picLocks.NoChangeAspect = true;
picLocks.NoChangeArrowheads = true;
NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
nvpdp.PictureLocks = picLocks;
NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
nvpp.NonVisualDrawingProperties = nvdp;
nvpp.NonVisualPictureDrawingProperties = nvpdp;
DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();
BlipFill blipFill = new BlipFill();
DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
blip.Embed = dp.GetIdOfPart(imgp);
blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
blipFill.Blip = blip;
blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
blipFill.Append(stretch);
DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
offset.X = 0;
offset.Y = 0;
t2d.Offset = offset;
DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
//Bitmap bitmap = new Bitmap(ms);
if (width == null)
extents.Cx = (long)bitmap.Width * (long)((float)914400 / bitmap.HorizontalResolution);
else
extents.Cx = width * (long)((float)914400 / bitmap.HorizontalResolution);
if (height == null)
extents.Cy = (long)bitmap.Height * (long)((float)914400 / bitmap.VerticalResolution);
else
extents.Cy = height * (long)((float)914400 / bitmap.VerticalResolution);
bitmap.Dispose();
t2d.Extents = extents;
ShapeProperties sp = new ShapeProperties();
sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
sp.Transform2D = t2d;
DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
sp.Append(prstGeom);
sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());
DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
picture.NonVisualPictureProperties = nvpp;
picture.BlipFill = blipFill;
picture.ShapeProperties = sp;
Position pos = new Position();
pos.X = x * 914400 / 72;
pos.Y = y * 914400 / 72;
Extent ext = new Extent();
ext.Cx = extents.Cx;
ext.Cy = extents.Cy;
AbsoluteAnchor anchor = new AbsoluteAnchor();
anchor.Position = pos;
anchor.Extent = ext;
anchor.Append(picture);
anchor.Append(new ClientData());
wsd.Append(anchor);
wsd.Save(dp);
}
catch (Exception ex)
{
throw ex; // or do something more interesting if you want
}
}
If I invoke the first method(use real file on the disk), it's ok, I can insert my picture into excel file. But if I read the file into memorystream and invoke method2, I can see the picture rectangle with error message.
So my question is how can I insert picture into excel via memorystream? Because I won't create too many files on disk.
I believe you need to create bitmap image data from stream first
There's a solution already for that here on Stack Overflow: Byte Array to Bitmap Image
I copy-paste the code from the solution:
int w= 100;
int h = 200;
int ch = 3; //number of channels (ie. assuming 24 bit RGB in this case)
byte[] imageData = new byte[w*h*ch]; //you image data here
Bitmap bitmap = new Bitmap(w,h,PixelFormat.Format24bppRgb);
BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
IntPtr pNative = bmData.Scan0;
Marshal.Copy(imageData,0,pNative,w*h*ch);
bitmap.UnlockBits(bmData);
OK, I think I have found solution.
I change memorystream parameter to string, and convert it to memorystream like below:
MemoryStream ms = new System.IO.MemoryStream(System.Convert.FromBase64String(str))
Now, it works.
I learn it from open xml sdk 2.5 productivity tool.

How to print the details in landscape in pdf using itextsharp?

My requirement is to print the details in landscape,not the page rotation.i need content printed in landscape.
Document doc = new Document(iTextSharp.text.PageSize.A4, (float)MarginLeft, (float)MarginRight, (float)MarginTop, (float)MarginBottom);
//210 mm width * 297 mm height
PaperWidthAvailable = iTextSharp.text.Utilities.MillimetersToPoints(210f) - ((float)MarginLeft + (float)MarginRight);
PaperHeightAvailable = iTextSharp.text.Utilities.MillimetersToPoints(297f) - ((float)MarginTop + (float)MarginBottom);
wdtOFcell = (float)BarcodeWidth + (float)BarcodeSpaceHorizontal;
colNo = (int)Math.Floor(PaperWidthAvailable / wdtOFcell);
TableWidth = wdtOFcell * colNo;
htOFcell = (float)BarcodeHeight + (float)BarcodeSpaceVertical;
PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
doc.Open();
int noOfColumns = colNo;
// int additionalRow = imageBarcodeLists.Count % noOfColumns;
int i = 1;
PdfPTable table = new PdfPTable(noOfColumns);
table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
table.HorizontalAlignment = 0;
table.TotalWidth = TableWidth;
table.LockedWidth = true;
float[] widths = new float[colNo];
for (int j = 0; j < colNo; j++)
{
widths[j] = wdtOFcell;
}
table.SetWidths(widths);
iTextSharp.text.Image itextBarcodeImage = null;
foreach (System.Drawing.Image barcodeImage in imageBarcodeLists)
{
var imageCompressor = new ImageCompressionUtility();
System.Drawing.Image barcodeImages = imageCompressor.TrimImageWhiteSpacesFromImage(barcodeImage);
itextBarcodeImage = iTextSharp.text.Image.GetInstance(barcodeImages, BaseColor.BLUE);
itextBarcodeImage.ScaleAbsolute((float)BarcodeWidth, (float)BarcodeHeight);
PdfPCell cells = new PdfPCell(itextBarcodeImage);
cells.Border = iTextSharp.text.Rectangle.NO_BORDER;
cells.PaddingTop = 0f;
cells.PaddingRight = 0f;
cells.PaddingBottom = 0f;
cells.PaddingLeft = 0f;
cells.UseAscender = true;
cells.FixedHeight = htOFcell;
cells.BackgroundColor = BaseColor.WHITE;
cells.Border = iTextSharp.text.Rectangle.NO_BORDER;
table.AddCell(cells);
i++;
}
doc.Add(table);
doc.Close();
The constant iTextSharp.text.PageSize.A4 is actually a Rectangle that is created like this:
public static readonly Rectangle A4 = new Rectangle(595,842);
If you want to rotate the page, you can use the Rotate() method as explained in my answer to this question: How to print custom page size as portrait in itextsharp
However, based on your comment "it rotates only the paper not the content written", you may be looking for a page size that is created like this:
Rectangle myA4 = new Rectangle(842,595);
Document doc = new Document(myA4);
If that doesn't work, please take a look at my answer to the question iText - Rotate page content while creating PDF
In that answer, I introduce a page rotation using a page event:
public class MyPdfPageEvent : iTextSharp.text.pdf.PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
writer.AddPageDictEntry(PdfName.ROTATE, PdfPage.SEASCAPE);
}
}
If none of the above has the effect you desire, you should improve your question (or it will be closed as "unclear what is asked").

Categories

Resources