path to resources directory in xamarin.android - xamarin.android

I need the path to my resources directory to access my fonts folder inside it like the one in this code:
PdfFont russian = PdfFontFactory.createFont(
"src/main/resources/fonts/FreeSans.ttf", "CP1251", true);
but in Xamarin.android. I tried the following:
string uri = "android.resource://" + this.PackageName + "/font/ARIAL.TTF";
PdfFont russian = PdfFontFactory.CreateFont(
uri, "CP1251", true);
but it doesn't work. I tried this code too:
var path2 = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
filePath = System.IO.Path.Combine(path2.ToString(), "myfile4.pdf");
stream = new FileStream(filePath, FileMode.Create);
PdfWriter writer = new PdfWriter(stream);
PdfDocument pdf2 = new iText.Kernel.Pdf.PdfDocument(writer);
Document document2 = new Document(pdf2, PageSize.A4);
AssetManager assets = this.Assets;
string content;
Stream stream2 = assets.Open("ARIAL.TTF");
var memorystrm = new MemoryStream();
stream2.CopyTo(memorystrm);
byte[] t = memorystrm.ToArray();
Toast.MakeText(this, t.Length.ToString(), ToastLength.Long);
if (t != null)
{
PdfFont russian = PdfFontFactory.CreateFont(t, "UTF-8", true);
document2.SetFont(russian);
Paragraph p = new Paragraph("Hello World! ")
.Add(new Text("صباح! ").SetFontSize(14)).Add(new Text("Bonjour le monde! ").SetFontSize(10));
document2.Add(p);
document2.Close();
Toast.MakeText(this, "done", ToastLength.Long);
}
else
{
Toast.MakeText(this, "error", ToastLength.Long);
}
no code was exceuted

The path of the folder of the Xamarin.Android project is different with the native Android project.
If you want to save the font file in the project to access the file, try to save the files in the Asset folder.Set the Build Action for this files to AndroidAsset.
string content;
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader(assets.Open("read_asset.txt")))
{
content = sr.ReadToEnd();
}
Check the tutorial:
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/resources-in-android/android-assets?tabs=windows
Update
i'll add my code, it didn't work. no code was executed
It seems that you forgot to add the .Show() code such as Toast.MakeText(this, "done", ToastLength.Long).Show().

Related

Trouble exporting to excel from mvc action

I created a simple action to download some content as excel file:
public FileResult ExportToExcel()
{
string filename = "list.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
List<string[]> list = new List<string[]>();
list.Add(new[] { "col1", "col2", "cols3" });
list.Add(new[] { "col4", "col5", "cols6" });
list.Add(new[] { "col7", "col8", "cols9" });
StringWriter sw = new StringWriter();
sw.WriteLine("ID,Date,Description");
foreach (string[] item in list)
{
sw.WriteLine("{0},{1},{2}", item[0], item[1], item[2]);
}
byte[] fileContents = Encoding.UTF8.GetBytes(sw.ToString());
return this.File(fileContents, contentType, filename);
}
I have 2 issues with it:
1. The file is downloaded but I cannot open it and am getting a warning:
Excel cannot open the file ... because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
When I use old excel format:
string filename = "List.xls";
string contentType = "application/vnd.ms-excel";
I am able to open the file but after 3 different warnings about file being corrupted etc.
Btw I compared saving and tried to write file as pdf
string filename = "List.pdf";
string contentType = "application/pdf";
And I still couldn't open the file - it said format is not valid etc.
2. The contents appear in the file in the second example however the commas are not recognised as column separators and all data in a row is written as one column.
What separator to use for excel format or how to write data to file to have it in a table excel format?
Ideal solution for me would be just return exported view (strongly typed) but I didn't find out how to do it so far.
--- EDIT: Working solution ---
public FileResult ExportToExcel()
{
string filename = "List.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
List<string[]> titles = new List<string[]>() { new[] { "a", "be", "ce" } };
List<string[]> list = new List<string[]>
{
new[] { "col1", "col2", "cols3" },
new[] { "col4", "col5", "cols6" },
new[] { "col7", "col8", "cols9" },
new[] { "col10", "col11", "cols12" }
};
XLWorkbook wb = new XLWorkbook();
XLTables xt = new XLTables();
var ws = wb.Worksheets.Add("List");
ws.Cell(1, 1).InsertData(titles);
ws.Cell(2, 1).InsertData(list);
ws.Columns().AdjustToContents();
var stream = new MemoryStream();
wb.SaveAs(stream);
stream.Seek(0, SeekOrigin.Begin);
wb.Dispose();
return this.File(stream, contentType, filename);
}
The reason why it is not being correctly rendered is because you cannot just return the mime type and expect the framework to figure out the rest.
I would go with a nuget package called closedXML which will allow you to create an excel file in memory and stream it back to the client.
it comes with a full documentation (here) for more information.
Using this package you can do something like
XLWorkbook wb = new XLWorkbook();
XLTables xt = new XLTables();
var ws = wb.Worksheets.Add("Sheet 1");
var firstCell = ws.Cell(1, 1);
var lastCell = ws.Cell(3, list.Count);
var table = ws.Range(firstCell.Address, lastCell.Address).AsTable();
table.Cell(2, 1).InsertData(list);
table.CreateTable();
ws.Columns().AdjustToContents();
using(var stream = new MemoryStream())
{
wb.SaveAs(stream);
stream.Seek(0, SeekOrigin.Begin);
wb.Dispose();
return File(stream , contentType, filename);
}

can eml directly open with outlook, instead eml file will download then click it to open in outlook?

I have an asp.net MVC application, below code works file.
But the code is that, When navigate to Email action in browser, an EML file is download, then when we click on that file, the file will open with outlook.
Can it be possible, when action calls, then EML file will directly open with outlook, instead of download and then click to open??
Code
public async Task<FileStreamResult> Email()
{
string dummyEmail = "test#localhost.com";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(dummyEmail);
mailMessage.To.Add("dejan.caric#gmail.com");
mailMessage.Subject = "Test subject";
mailMessage.Body = "Test body";
// mark as draft
mailMessage.Headers.Add("X-Unsent", "1");
// download image and save it as attachment
using (var httpClient = new HttpClient())
{
var imageStream = await httpClient.GetStreamAsync(new Uri("http://dcaric.com/favicon.ico"));
mailMessage.Attachments.Add(new Attachment(imageStream, "favicon.ico"));
}
var stream = new MemoryStream();
ToEmlStream(mailMessage, stream, dummyEmail);
stream.Position = 0;
return File(stream, "message/rfc822", "test_email.eml");
}
private void ToEmlStream(MailMessage msg, Stream str, string dummyEmail)
{
using (var client = new SmtpClient())
{
var id = Guid.NewGuid();
var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);
tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp");
// create a temp folder to hold just this .eml file so that we can find it easily.
tempFolder = Path.Combine(tempFolder, id.ToString());
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
client.UseDefaultCredentials = true;
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = tempFolder;
client.Send(msg);
// tempFolder should contain 1 eml file
var filePath = Directory.GetFiles(tempFolder).Single();
// create new file and remove all lines that start with 'X-Sender:' or 'From:'
string newFile = Path.Combine(tempFolder, "modified.eml");
using (var sr = new StreamReader(filePath))
{
using (var sw = new StreamWriter(newFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (!line.StartsWith("X-Sender:") &&
!line.StartsWith("From:") &&
// dummy email which is used if receiver address is empty
!line.StartsWith("X-Receiver: " + dummyEmail) &&
// dummy email which is used if receiver address is empty
!line.StartsWith("To: " + dummyEmail))
{
sw.WriteLine(line);
}
}
}
}
// stream out the contents
using (var fs = new FileStream(newFile, FileMode.Open))
{
fs.CopyTo(str);
}
}
}
With Chrome you can make it automatically open certain files, once they are downloaded.
.EML should attempt to open in Outlook.
I am not sure about other browsers, but Chrome seemed to be the only one with this option.
It's not a pefect solution because if someone downloaded an .EML from another website in Chrome, it will open automatically aswell.
I recommend having Chrome dedicated to your Web application.
You sure can open local .eml file with Outlook.
But in context of web application, you must firstly download it.

How to make the .xlsx file download

The below is used to create the .xls file and download the file.
I want to download it to .xlsx file. If i simply change the extension into ".xlsx", the report directly opens in the browser. I want it to open in .xlsx extension. Kindly help me.
Below is the code reference for you,
//setting the application path to a variable
strPath = Server.MapPath("ExcelFiles");
//Creating a file name
strExportPath = "Card" + intRnd.ToString() + intRnd1.ToString() + ".xls";
hidFilePath.Value = "ExcelFiles/" + strExportPath;
//Creating the full path with the filename
strExcelPath = strPath + "\\" + strExportPath;
Session["AK_SC_CRD_EXCEL_PATH"] = strExcelPath;
StreamWriter objStreamWriter = new StreamWriter(strExcelPath, true);
//Write the XL Contents to a stream writer.
objStreamWriter.WriteLine(strXLContents);
objStreamWriter.Close();
objStreamWriter = null;
Thanks.
You may need to add a MIMETYPE for xslx to your response.
.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Similar to below;
Response.ContentType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Adding Following code will force your file download instead of opening in the browser.
Response.AddHeader("content-disposition", "attachment;filename=yourfilename.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/*Add your code here to write file to response stream*/
Response.End();
Use following code to download Excel:-
HttpContext context = HttpContext.Current;
FileStream fs = null;
BinaryReader br = null;
byte[] data = null;
try
{
if (File.Exists(filePath))
{
FileInfo file = new FileInfo(filePath);
fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
br = new BinaryReader(fs, System.Text.Encoding.Default);
data = new byte[Convert.ToInt32(fs.Length)];
br.Read(data, 0, data.Length);
context.Response.Clear();
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("content-disposition", "attachment; filename=" + file.FullName);
context.Response.AddHeader("Content-Length", file.Length.ToString());
context.Response.BinaryWrite(data);
context.Response.Flush();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Error in File downloading file from a folder in MVC2

I am encountering a problem in getting the download prompt. In the below code first am allowing the user to upload a file to compress. Once the file is compressed the user should be provided with the compressed files. But in the below code download prompt doesn't appears neither it shows any error. Please help me by correcting my code
The view code:
function CompressFile(box) {
var file = document.getElementById('fileComp');
if (file.value == "") {
alert("Choose a file to upload");
return false;
}
dhtmlx.modalbox.hide(box);
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Compress', true);
xhr.send(fd);
}
The controller code:
public ActionResult Compress(HttpPostedFileBase file)
{
var supportedType = new[] { "pdf" };
var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
var filename = Path.GetFileNameWithoutExtension(file.FileName) ?? "";
if (file.ContentLength > 0 && supportedType.Contains(fileExt))
{
string filePath = Path.Combine(HttpContext.Server.MapPath(_uploadPDF), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
PdfReader reader = new PdfReader(filePath);
string name = DateTime.Now.ToString("ddMM_HHmmss");
name = Server.MapPath(_fileUploadPath + name + ".pdf");
PdfStamper stamper = new PdfStamper(reader, new FileStream(name, FileMode.Create), PdfWriter.VERSION_1_5);
stamper.FormFlattening = true;
stamper.SetFullCompression();
stamper.Close();
string fn = System.IO.Path.GetFileName(name);
return base.File(name, "application/pdf",fn);
}
else
{
return View();
}
}
The problem is that you're using Ajax. You can't download a file through Ajax. You need to do a regular POST to the ActionMethod. That way the browser can send you back the file and prompt the user where he wants to save it.

Error in converting HTML with images to PDF using itextsharp

In my application first am allowing the user to create html document using CKEDITOR where user can can create html document and can insert image, form fields etc. the generated HTML document is than converted into PDF.
If HTML document contains plain text than PDF file gets created successfully but if user inserts image in it than gives error.
code for creating PDF document.
public ActionResult CreateFile(FormCollection data)
{
var filename = data["filename"];
var htmlContent = data["content"];
string sFilePath = Server.MapPath(_createdPDF + filename + ".html");
htmlContent = htmlContent.Trim();
if (!System.IO.File.Exists(sFilePath))
{
using (FileStream fs = new FileStream(sFilePath, FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.Write(htmlContent);
}
}
createPDF(sFilePath);
}
return View();
}
private MemoryStream createPDF(string sFilePath)
{
string filename = Path.GetFileNameWithoutExtension(sFilePath);
string name = Server.MapPath(_createdPDF + filename + ".pdf");
MemoryStream ms = new MemoryStream();
TextReader tr = new StringReader(sFilePath);
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
string urldir = Request.Url.GetLeftPart(UriPartial.Path);
urldir = urldir.Substring(0, urldir.LastIndexOf("/") + 1);
Response.Write(urldir);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(name, FileMode.Create));
document.Open();
string htmlText = "";
StreamReader sr;
sr = System.IO.File.OpenText(sFilePath);
htmlText = sr.ReadToEnd();
sr.Close();
WebClient wc = new WebClient();
Response.Write(htmlText);
var props = new Dictionary<string, Object>();
props["img_baseurl"] = #"C:\Documents and Settings\shubham\My Documents\visdatemplatemanger\visdatemplatemanger\";
List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null,props);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
document.Close();
System.IO.File.Delete(sFilePath);
UploadURL(name);
return ms;
}
The error that i get if image is included in HTML document is:
Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\PDFimages\rectangle-shape.png'.
iTextSharp will try to resolve relative images for HTTP-based documents but ones served from the filesystem you need to either provide absolute paths or provide a base for it to search from.
//Image search base, path will be concatenated directly so make sure it contains a trailing slash
var props = new Dictionary<string, Object>();
props["img_baseurl"] = #"c:\images\";
//Include the props from above
htmlarraylist = HTMLWorker.ParseToList(sr, null, props);

Resources