How to add an Image to a PDF document? - asp.net

I am using iTextSharp to join multiple pdfs together that are from microsofts report viewer. page.AddImage(image__1) in the code below is throwing an error Object reference not set to an instance of an object. I am not seeing what is set to nothing. Is there a different way that I can join reports from the report viewer and add a watermark image?
mybytes = MSRptViewer1.LocalReport.Render("PDF", Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
reader = New iTextSharp.text.pdf.PdfReader(mybytes)
numberOfPages = reader.NumberOfPages
currentPageNumber = 0
Dim imageFile As String = Server.MapPath("WaterMark.png")
Dim buffer As Byte() = IO.File.ReadAllBytes(imageFile)
Dim image__1 As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(buffer)
image__1.SetAbsolutePosition(100, 100)
Do While (currentPageNumber < numberOfPages)
currentPageNumber += 1
doc.SetPageSize(PageSize.LETTER)
doc.NewPage()
page = writer.GetImportedPage(reader, currentPageNumber)
page.AddImage(image__1)
rotation = reader.GetPageRotation(currentPageNumber)
If (rotation = 90) Or (rotation = 270) Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(currentPageNumber).Height)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
Loop

<?php $data = file_get_contents('https://static1.squarespace.com/static/56c775ad27d4bd3fdb24775d/t/5a8b201324a694d7071662ee/1519067160925/dummy+logo.jpg');
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
?>
this method for image convert to base64 format
<?php echo '<div class="company-logo"><img src="'.$base64.'" alt="base" /></div>'; ?>
or
<img src="<?php echo $base64; ?>" alt="base" />

I have asked my Publisher, Manning Publications, to offer chapter 6 of my book for free. I know this chapter only shows you examples in Java, but all the examples were ported to C# for your convenience.
If you read this chapter, you'll find out that you're making the following mistakes:
You are using PdfReader/PdfWriter to add content to an existing document instead of PdfReader/PdfStamper. If you want a nice watermark example, take a look at the ManipulatePdf method in the StampStationery.cs example. Replace background.addTemplate() with background.addImage() to add an image instead of a background page taken from another PDF. You'll also learn more about using an image as a watermark here: How to add a watermark to a PDF file?
You are using PdfReader/PdfWriter to concatenate existing documents instead of PdfCopy. By doing so, you risk all kinds of problems: e.g. parts of pages being cut off, links being removed, annotations getting lost,... Please read my answer to this question: How to merge documents correctly?
You are ignoring the fact that PdfImportedPage is read-only. You can only add content in the context of PdfCopy after creating a PageStamp object. Please take a look at the ConcatenateStamp.cs example.
Summarized: your question is more or less a duplicate of (a combination of) other questions answered before on StackOverflow. It seems that you copy/pasted some code from a source that isn't one of the official sources of documentation.

Related

VB.net aspX image resize and created file permission denied

I'm trying to create an image based on an original image as a template.
a picture > kapak.jpg - resize to 1366x768 > orta.jpg - resize to 848x480
Code is working. Nothing wrong BUT when I use; code block 2 its locking the file which is kapak.jpg
I can't delete or rename etc. Even if I close the browser or vstudio or all. Nothing changes but restart the iis. I even cant delete it on the file browser as well. It's just locking it and doesnt allow anything. it says that; w3wp.exe or iis express worker is using this file so you cant delete or etc. Access denied.
I tried dispose or =nothing for bitmap
moved code block 2 to another sub
nothing changed.
If I dont use code block 2 it creates and allows me to delete or rename etc.
Any suggestions will be appreciated. How can I set free the file?
button_1_click
gelenIMG.ImageUrl = "\dene_2.jpg"
Dim uzatBOYfark As Integer
Dim uzatENfark As Integer
Dim kapakRESIMayar As New Rectangle(0, 0, 1366, 768)
uzatENfark = kapakRESIMayar.Width : uzatBOYfark = kapakRESIMayar.Height
Using orijinalRESIM = Image.FromFile(Server.MapPath(gelenIMG.ImageUrl))
If orijinalRESIM.Width < kapakRESIMayar.Width Then uzatENfark = kapakRESIMayar.Width * (kapakRESIMayar.Width / orijinalRESIM.Width)
If orijinalRESIM.Height < kapakRESIMayar.Height Then uzatBOYfark = kapakRESIMayar.Height * (kapakRESIMayar.Height / orijinalRESIM.Height)
Using kapakZEMINsablon = New Bitmap(kapakRESIMayar.Width, kapakRESIMayar.Height)
Using grp = Graphics.FromImage(kapakZEMINsablon)
grp.Clear(Color.Red)
grp.DrawImage(orijinalRESIM, New Rectangle(0, 0, uzatENfark, uzatBOYfark + 1), kapakRESIMayar, GraphicsUnit.Pixel)
End Using
kapakZEMINsablon.Save(Server.MapPath(geciciRESIMyeri & "\kapak.jpg"), Imaging.ImageFormat.Jpeg)
End Using
End Using
imgKAPAK.ImageUrl = geciciRESIMyeri & "\kapak.jpg"
code block 2:
Dim bitmapORTA As New Bitmap(Image.FromFile(Server.MapPath(imgKAPAK.ImageUrl), True), 848, 480)
bitmapORTA.Save(Server.MapPath(geciciRESIMyeri & "\orta.jpg"), Imaging.ImageFormat.Jpeg)
imgORTA.ImageUrl = geciciRESIMyeri & "\orta.jpg"

InDesign - Script to find specific words between angle brackets, and copy those to a list

Sorry in advance if I’m not phrasing this question correctly. I know nothing about InDesign scripting, but this would solve a workflow problem I’m having at my company, so I would appreciate any and all help.
I want to find all strings in an InDesign file that are between angle brackets (i.e. <variable>) and export that out into a list. Ideally this list would be a separate document but if it can just be dumped into a text frame or something that’s fine.
Any ideas on how to do this? Thank you in advance for any and all help.
Here is something simple:
app.findGrepPreferences=NothingEnum.NOTHING; //to reset the Grep search
app.findGrepPreferences.findWhat = '<[^<]+?>'; //the word(s) you are searching
var fnd = app.activeDocument.findGrep (); //execute search
var temp_str = ''; //initialize an empty string
for (var i = 0; i < fnd.length; i++) { //loop through results and store the results
temp_str += fnd[i].contents.toString() + '\r'; // add next found item text to string
}
var new_doc = app.documents.add (); //create a new document
app.scriptPreferences.measurementUnit = MeasurementUnits.POINTS; //set measurement units to points
var text_frame = new_doc.pages[0].textFrames.add({geometricBounds:[0,0,100,100]});// create a new text frame on the first page
text_frame.contents = temp_str; //output your text to the text frame in the new document
For more data see here.

Pdf Generation Using ITextSharp for Cheque Like Structure

I have requirement of online cheque generation.
I am using ,
using iTextSharp.text;
using iTextSharp.text.pdf;
I have dynamic cheque Height and width,font and fontsize.
And obviously cheque number with account information in all page of document.
My code goes like this
Document doc = new Document(new Rectangle(width, height), 0, 0, 0, 0);
string path = Server.MapPath("~/REPORTFILES");
var writer = PdfWriter.GetInstance(doc, new FileStream(path + "/cheque.pdf",FileMode.Create));
doc.Open();
BaseFont f_cn = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
for (int i = fromchq; i <= tochq; i++)
{
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
cb.SetFontAndSize(f_cn, 14);
cb.SetFontAndSize(f_cn, fontsize);
cb.SetTextMatrix(cord_x, cord_y);
cb.ShowText(getProperty(propertyName,i.ToString().PadLeft(FromChqNo.Length, '0')));
cb.EndText();
doc.NewPage();
}
Here cord_x and cord_y is the co-ordinate location of that text.
Everything works fine i got pdf of my custom size.
like this :
But while printing it into the cheque
its work fine untill it has space enough to print single page. my xps image is attached bellow.
Area in red curve is skiped to be printed.
I mean to ask how can i make it posible that it will print serially, and completely fullfill my requirement that a cheque leaf of any height ,width,font will be printed serially. Thank you all in advance and also thanks for reading my problem.

Unable to Create Image of Special Characters

I have written a imageHandler.ashx in c# which draw image of a text on a fly . Its takes a parameter string txt. The Handler is called from Asp.net page. At the time of calling, if text contains the character # or any special character .it Does not create the images of #,or any special character's given to it.
According to my R&D the problem is with a Graphics.DrawString() method some how its is unable to write special characters.so please tell me how to create a image of a special characters
Code I am using :
String signatureText = HttpUtility.HtmlDecode(signatureText);
System.Drawing.Text.PrivateFontCollection fontCollection = new System.Drawing.Text.PrivateFontCollection();
FontFamily ff1 = fontCollection.Families[0];
// Initialize graphics
RectangleF rectF = new RectangleF(0, 0, imgWidth, imgHeight);
Bitmap pic = new Bitmap((int) rectF.Width,imgHeight, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(pic);
//g.SmoothingMode = SmoothingMode.Default;
// g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
Font font1 = new Font(ff1, imgHeight, FontStyle.Regular, GraphicsUnit.Pixel);
float bestFontSize = BestFontSize(g, new Size(imgWidth, imgHeight), font1, signatureText);
Font font2 = new Font(ff1, bestFontSize, FontStyle.Regular, GraphicsUnit.Pixel);
// Set colors
Color fontColor = Color.Black;
Color rectColor = Color.White;
SolidBrush fgBrush = new SolidBrush(fontColor);
SolidBrush bgBrush = new SolidBrush(rectColor);
// Rectangle or ellipse?
g.FillRectangle(bgBrush, rectF);
// Set font direction & alignment
StringFormat format = new StringFormat();
//format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
// Finally, draw the font
g.DrawString(signatureText, font2, fgBrush, rectF, format);
pic = (Bitmap) ImageUtility.ResizeImageWithAspectRatio(pic, imgWidth, imgHeight, true);
pic.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Any help is Appreciated Thanks in Advance
DrawString() don't have any problem while writing special characters if they are provided in font file (.ttf)
Problem can be in the following line
System.Drawing.Text.PrivateFontCollection fontCollection = new System.Drawing.Text.PrivateFontCollection();
Specially with the font you get in ff1
FontFamily ff1 = fontCollection.Families[0];
In your case it means Font ff1 don't have representation for some or all special characters.
Since I don't know how many font files you are getting from fontCollection.Families, if fontCollection.Families contain more than one font file try next one.
FontFamily ff1 = fontCollection.Families[1]; // and so on.
Or try to add font file with all special characters (if System.Drawing.Text.PrivateFontCollection is absolutely necessary ).
Alternatively you can use InstalledFontCollection instead of PrivateFontCollection
System.Drawing.Text.InstalledFontCollection fontCollection = new System.Drawing.Text.InstalledFontCollection();
Which will give you all installed fonts of the system on which application is running through its Families property InstalledFontCollection.
Easiest way is (if only one font is required, as you are using only one font in your provided code)
using constructor of FontFamily class with a string type parameter FontFamily.
Consider replacing this line
FontFamily ff1 = fontCollection.Families[0];
With this one
FontFamily fontFamily1 = new FontFamily("Arial");
Arial must be installed on the system where application is running.
Hope this will help.
DrawString doesn't have any problem with drawing special characters like # or copyright (I just tested it and produced the image below).
The problem might be from your URL parameter. Try encoding your text using Server.UrlEncode when passing the text, and then Server.UrlDecode before giving it to DrawString.

How to remove the full file path from YSOD?

In the YSOD below, the stacktrace (and the source file line) contain the full path to the source file. Unfortunately, the full path to the source file name contains my user name, which is firstname.lastname.
I want to keep the YSOD, as well as the stack trace including the filename and line number (it's a demo and testing system), but the username should vanish from the sourcefile path. Seeing the file's path is also OK, but the path should be truncated at the solution root directory.
(without me having to copy-paste the solution every time to another path before publishing it...)
Is there any way to accomplish this ?
Note: Custom error pages aren't an option.
Path is embedded in .pdb files, which are produced by the compiler. The only way to change this is to build your project in some other location, preferably somewhere near the build server.
Never mind, I found it out myself.
Thanks to Anton Gogolev's statement that the path is in the pdb file, I realized it is possible.
One can do a binary search-and-replace on the pdb file, and replace the username with something else.
I quickly tried using this:
https://codereview.stackexchange.com/questions/3226/replace-sequence-of-strings-in-binary-file
and it worked (on 50% of the pdb files).
So mind the crap, that code-snippet in the link seems to be buggy.
But the concept seems to work.
I now use this code:
public static void SizeUnsafeReplaceTextInFile(string strPath, string strTextToSearch, string strTextToReplace)
{
byte[] baBuffer = System.IO.File.ReadAllBytes(strPath);
List<int> lsReplacePositions = new List<int>();
System.Text.Encoding enc = System.Text.Encoding.UTF8;
byte[] baSearchBytes = enc.GetBytes(strTextToSearch);
byte[] baReplaceBytes = enc.GetBytes(strTextToReplace);
var matches = SearchBytePattern(baSearchBytes, baBuffer, ref lsReplacePositions);
if (matches != 0)
{
foreach (var iReplacePosition in lsReplacePositions)
{
for (int i = 0; i < baReplaceBytes.Length; ++i)
{
baBuffer[iReplacePosition + i] = baReplaceBytes[i];
} // Next i
} // Next iReplacePosition
} // End if (matches != 0)
System.IO.File.WriteAllBytes(strPath, baBuffer);
Array.Clear(baBuffer, 0, baBuffer.Length);
Array.Clear(baSearchBytes, 0, baSearchBytes.Length);
Array.Clear(baReplaceBytes, 0, baReplaceBytes.Length);
baBuffer = null;
baSearchBytes = null;
baReplaceBytes = null;
} // End Sub ReplaceTextInFile
Replace firstname.lastname with something that has equally many characters, for example "Poltergeist".
Now I only need to figure out how to run the binary search and replace as a post-build action.

Resources