Set images on Pdf using itextsharp - asp.net

I am working on WCF service to create a pad file and want to set image on created pdf.
Below is my code. it gives me error "object reference not set to an object instance"
string str = System.Web.HttpContext.Current.Request.MapPath("App_Data/suc.png");
Image imgCheckBoxChecked = Image.GetInstance(str);
The other thing I try and it gives me error :Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\suc.png: Below is my other code
Image imgCheckBoxChecked = Image.GetInstance("App_Data/suc.png");
cell.AddElement(imgCheckBoxChecked);
cell.Colspan = 4;
table.AddCell(cell);
Any idea on how to solve this error and set image on pdf.
Thanks

You can use AppDomain.BaseDirectory to get directory to the main dll, after this you can use it to get the path to your image dll, like Path.Combine(AppDomain.BaseDirectory, "App_Data\\suc.png"), if you host service in ASP.NET, and the dll is in Bin directory you can use relative path like Path.Combine(AppDomain.BaseDirectory, "..\\App_Data\\suc.png")

string pdfPath = "~/PDF/File_1.pdf";
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/image.JPG"));
img.ScalePercent(100f);
Document doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath(pdfPath), FileMode.Create));
doc.Open();
doc.Add(new Paragraph(sb.ToString()));
doc.Add(img);
doc.Close();

Related

Save an Image with a new file name [ImageSharp]

I have upgraded my project from .net framework to .net 6 (core). In my project, there are many places where Bitmap is used. I have read in the microsoft documentations that System.Drawing.Common will only support the Windows platform and even after adding the EnableUnixSupport configuration, it will not be supported in net7.So, now I am using ImageSharp.Web. I have the scenario where I save a file as Image (the format is .tiff) then I read from that path as bitmap and save as PNG ( due to some business rule)
Following is the line of code I am trying change:
Bitmap.FromFile(completePath).Save(pngPath, ImageFormat.Png);
This is the code I have converted into. The only issue is how to save as a new file name as the Tiff file has tiff in the file name.
string extension = _GetExtension(img.ContentType);
if (extension == Constants.TiffExtension)
{
fileName = fileName.Replace(Constants.TiffExtension, "PNG");
using (var outputStream = new FileStream(completePath, FileMode.CreateNew))
{
var image = SixLabors.ImageSharp.Image.Load(completePath);
image.SaveAsync(outputStream, new PngEncoder()); //how to save new file name?
}
}
You can use the image.Save(fileName); overload to save a image to a file. The file name overload that takes just a path will automatically choose the correct encoder based on the file extension.
I was using the ImageSharp.Web package while the one I needed was the basic ImageSharp package. Special thanks to #James South for correcting me and #tocsoft for the guidance.
I have fixed it by the following code which is working:
if (extension == Constants.Conversion.TiffExtension)
{
using (SixLabors.ImageSharp.Image image = SixLabors.ImageSharp.Image.Load(completePath))
{
string pngPath = completePath.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
image.Save(pngPath);
fileName = fileName.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
}
}

What is the path of the Json file in Android at Xamarin.Forms?

I am developing an application for Android using Xamarin.
I have created a JsonData folder in the Android project and created a Setting.json file.
\MyApp\MyApp.Android\JsonData\Setting.json
In the properties, we set the Copy when new.
The following folders in the local environment contain the files.
\MyApp\MyApp.Android\bin\Debug\JsonData\Setting.json
I want to load this file in the actual Android device.
When I do this, it tells me that the file is missing.
Could not find a part of the path "/JsonData/Setting.json."
Try
{
var text = File.ReadAllText("JsonData/Setting.json", Encoding.UTF8);
var setting = JsonConvert.DeserializeObject<Setting>(text);
}
catch(Exception exception)
{
var error = exception.Message;
}
What is the path of the file in Android?
I think you're using File Handling in Xamarin.Forms incorrectly.
From the parameter of function File.ReadAllText, the app will access the file system to getSetting.json from folder JsonData in your android device.
The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
And you can read the file by code:
string text = File.ReadAllText(fileName);
In addition, from your code,I guess you want to Load your Embedded file( Setting.json) as Resources,right?
In this case,we should make sure the Build Action of your Setting.json is Embedded Resource.
And GetManifestResourceStream is used to access the embedded file using its Resource ID.
You can refer to the following code:
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAppName.JsonData.Setting.json");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
text = reader.ReadToEnd ();
}
For more , you can check document : File Handling in Xamarin.Forms.
And you can also check the sample code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithfiles/ .

XML does not get saved in asp.net

I have a problem saving my xml-file.
i use this XMLwriter :
using (XmlWriter writer = XmlWriter.Create("CarsXML.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("CarsXml");
foreach (Car item in cars)
{
writer.WriteStartElement("Car");
writer.WriteElementString("Brand", item.Brand);
writer.WriteElementString("Type", item.Type);
writer.WriteElementString("Price", item.Price);
writer.WriteElementString("Effect", item.Effect);
writer.WriteElementString("Year", item.year);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
}
Seems ok right? No compile errors..
I´ve also tried this just for testing :
XDocument doc = new XDocument(
new XElement("Root",
new XElement("Child", "content")
)
);
doc.Save("Root.xml");
Still no luck.. `ve trid this in a console app, and it works so the code must be fine..
I´ve also tried with a piece of code i found somewhere - using XmlDocument instead - but its the same deal.
What am i doing wrong?
When you are in a web application, the current directory is not the root directory of the web application. It's the directory where the IIS executable is, so that's somewhere in the Windows system directories.
Naturally you don't have write access to that directory from the web application, so you get some exception when you try to create a file there.
Specify the full path of the file that you want to create. You can use the MapPath method to get the physical path to a file from a virtual path. Example:
string fileName = Server.MapPath("/xmldata/CarsXML.xml");
using (XmlWriter writer = XmlWriter.Create(fileName))
...

Image to be loaded into pdf file created from Sharepoint Server Images Folder

I am using ItextSharp Library to generate pdf files on a button click on my SharePoint Site. I want to use a logo on the pdf whose image resides on the Images Folder of Sharepoint. I am unable to do that.
Can someone help me with it.
Below is the code that I am using which is getting the instance from window32 which I dont want.
protected void button1_OnClick(object sender, EventArgs e)
{
Font Arial = FontFactory.GetFont("Arial", 12, BaseColor.GREEN);
Font Verdana = FontFactory.GetFont("Verdana", 16, Font.BOLDITALIC, new BaseColor(125, 88, 15));
string imagepath = SPContext.Current.Web + "/_layouts/Images/Image1.png";
using (var ms = new MemoryStream())
{
using (var document = new Document(PageSize.A4,50,50,15,15))
{
PdfWriter.GetInstance(document, ms);
document.Open();
Paragraph img = new Paragraph();
Image jpg = Image.GetInstance(imagepath); --- Getting an error here stating "Could not find a part of the path 'c:\windows\system32\inetsrv\CustomSystem\_layouts\Images\Image1.png'"
img.Add(jpg );
}
}
}
Please help!
I'm not too familiar with SharePoint development but you're problem is with this line:
string imagepath = SPContext.Current.Web + "/_layouts/Images/Image1.png";
This string must be an absolute path path such as c:\www\sites\image.png, not a relative one which it is right now. I can tell its relative because when you ask ASP.Net to get something for you but you don't specify a path it looks in %WINDOWS%.
I don't know how you're using SPContext.Current.Web but according to the docs calling .ToString() on it returns the title of the website which is what would happen if you concatenated it with a string like you are. My guess is that you don't need that but could be wrong.
If the layouts folder is a subfolder of the folder that the file you are working on is in then you should be able to use Server.MapPath to get the absolute path:
string imagepath = Server.MapPath("_layouts/Images/Image1.png");
i have done like this in my sharepoint site
string url = "http://fspl-dsktp-038:8000/Style%20Library/FSPL/CorporateLogo.png";
//iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Server.MapPath("images") + "//images/FSPL LOGO.png");
iTextSharp.text.Image logo =iTextSharp.text.Image.GetInstance(url);
logo.ScaleAbsolute(90, 90);
Imagecell.AddElement(logo);
gvTable.AddCell(Imagecell);

File reading and writing inside asp.net web application

I have developed an ASP.NET web application in Visual Studio 2008.
I have an HTML document and one text file in the application, but both are not inside my application.
Both are outside, so when I try to run the same application in another system, I get an error because I am missing those files.
I want to include the files inside the application when I deploy it.
Below is the code I use to read and write the files:
//file write test.txt
FileStream file1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);
// Create a new stream to write to the file
StreamWriter sw1 = new StreamWriter(file1);
// Write a string to the file
sw1.Write(emailId);
// Close StreamWriter
sw1.Close();
// Close file
file1.Close();
// *** Write to file ***
// Specify file, instructions, and privelegdes
FileStream file = new FileStream("test.html", FileMode.Create, FileAccess.Write);
// Create a new stream to write to the file
StreamWriter sw = new StreamWriter(file);
// Write a string to the file
sw.Write(BodyLiteral.Text);
// Close StreamWriter
sw.Close();
// Close file
file.Close();
// *** Read from file ***
// Specify file, instructions, and privelegdes
file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read);
// Create a new stream to read from a file
StreamReader sr = new StreamReader(file);
// Read contents of file into a string
string cval = sr.ReadToEnd();
Response.Write(cval);
// Close StreamReader
sr.Close();
// Close file
file.Close();
//html file reading
string text = File.ReadAllText(#"D:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\test.html");
Both of my files are in: D:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\
How can I deploy these two files with application so that the program will work on another system?
Your best bet would be Server.MapPath().
Example:
Put the files inside folder "file" (you can make a folder in your solution, by right clicking your solution and choose add folder)..
then right click the folder..choose existing item , and then choose your files..
To make the path to your files local.. use the follow
Server.MapPath("~\\files\\test.html");
Your code modified
FileStream file = new FileStream( Server.MapPath("~\\files\\test.html"), FileMode.Create, FileAccess.Write);
Best thing to do is to add the files to your solution.
In solution exploere you can right-click and add an existing item. Change your code to read from that location, so when you deploy your code it will be in a known location and part of the deployment.

Resources