i am trying to make help for my application. I have xps documents which i am loading to documentviewer. These files are embedded in resource file.
I am able to access these as bytearray.
For example
Properties.Resources.help_sudoku_methods_2
returns byte[]
However, documentviewer cant read it and requires fixeddocumentsequence.
So i create memory stream from bytearray, then xpsdocument and then fixeddocumentsequence like this:
private void loadDocument(byte[] sourceXPS)
{
MemoryStream ms = new MemoryStream(sourceXPS);
const string memoryName = "memorystream://ms.xps";
Uri memoryUri = new Uri(memoryName);
try
{
PackageStore.RemovePackage(memoryUri);
}
catch (Exception)
{ }
Package package = Package.Open(ms);
PackageStore.AddPackage(memoryUri, package);
XpsDocument xps = new XpsDocument(package, CompressionOption.SuperFast, memoryName);
FixedDocumentSequence fixedDocumentSequence = xps.GetFixedDocumentSequence();
doc.Document = fixedDocumentSequence;
}
This is very unclean aproach and also doesnt work if there are images in files - instead of images in new documents displays images from first loaded doc.
Is there any cleaner way to load XPS from embedded resources to documentviewer? or do i need somethink like copy file from resources to application directory and load from here and not memorystream? Thank you.
why dont you write file to system temp folder and then read from there.
Stream ReadStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("file1.xps");
string tempFile = Path.GetTempPath()+"file1.xps";
FileStream WriteStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write);
ReadStream.CopyTo(WriteStream);
WriteStream.Close();
ReadStream.Close();
// Read tempFile INTO memory here and then
File.Delete(tempFile);
Related
I am trying extract the word document, It has embedded files(word,excel,package). I am not able to extract package and save it Using C# Open XML.
The below code just extracts word and excel but not package.
using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, false))
{
foreach (EmbeddedPackagePart pkgPart in document.MainDocumentPart.GetPartsOfType<EmbeddedPackagePart>())
{
if (pkgpart.uri.tostring().startswith(embeddingpartstring))
{
string filename1 = pkgpart.uri.tostring().remove(0, embeddingpartstring.length);
// get the stream from the part
system.io.stream partstream = pkgpart.getstream();
string filepath = "d:\\test\\" + filename1;
// write the steam to the file.
system.io.filestream writestream = new system.io.filestream(filepath, filemode.create, fileaccess.write);
readwritestream(pkgpart.getstream(), writestream);
}
}
}
The issue you're having is, that when you go to MainDocument.Parts and start searching, what you'll get is things like "Imagepart", "ChartPart" etc. where the ChartPart might have it's own embedded part, which could be the Excel or Word file you are looking for.
In short, you need to extend your search for embedded parts, to the actual parts in the mainDocument.
If I just wanted to extract all embedded parts in one of the files from my own project, I would go about it like this.
using (var document = WordprocessingDocument.Open(#"C:\Test\myTestDocument.docx", false))
{
//just grab all the parts, might be relevant to be a bit more clever about it, depending on sizes of files and how many files you want to search through
foreach(var part in document.MainDocumentPart.Parts)
{
//foreach part see if that part containts an EmbeddedPackagePart
var testForEmbedding = part.OpenXmlPart.GetPartsOfType<EmbeddedPackagePart>();
foreach(EmbeddedPackagePart embedding in testForEmbedding)
{
//You should probably insert some clever naming scheme here..
string fileName = embedding.Uri.OriginalString.Split('/').Last();
//stream the EmbeddedPackagePart to a file
using(FileStream myFile = File.Create(#"C:\test\" + fileName))
using (var stream = embedding.GetStream())
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(myFile);
myFile.Close();
}
}
}
}
I hope this helps!
I need to save the file when method OnDestroy is called and load same file when method OnCreate is called. At this time I can read json file easily from Assets (this works fine)
StreamReader reader = new StreamReader(Assets.Open("reiksmes.json"));
string JSONstring = reader.ReadToEnd();
Daiktai myList = JsonConvert.DeserializeObject<Daiktai>(JSONstring);
items.Add(myList);
, but I have some problems when I try to save(write) Daiktai class data to the same file I opened above. I tried:
string data = JsonConvert.SerializeObject(items);
File.WriteAllText("Assets\\reiksmes.json", data);
with this try I get error System.UnauthorizedAccessException: Access to the path "/Assets
eiksmes.json" is denied.
also tried:
string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));
writer.WriteLine(data);
and with this try I get error System.ArgumentException: Stream was not writable.
Summary:
I think I chose bad directory(Assets), I need to save and load data (json format). So where do I need to save them and how(give example)?
You can't save anything to assets. You can just read from it. You have to save the file to a different folder.
var fileName = "reiksmes.json";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, fileName);
Console.WriteLine(path);
if (!File.Exists(path))
{
var s = AssetManager.Open(fileName);
// create a write stream
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
// write to the stream
ReadWriteStream(s, writeStream);
}
I have a xlsx file (New.xlsx) in a folder (Common) in my project (Silverlight side).
I want to access that file path on button click event and want to open that file.
I used below path :
string path = #"/Common/New.xlsx";
string path1 = excel.Workbooks.Open(path);
excel.Visible = true;
But it is not working and I cannot open that file.
How to access file using file path in Silverlight?
You have a few options available to you for giving access to the file in question.
You can get the content of the file as a stream and then ask the user to save the file via the SaveFileDialog class. The user would then have to select where they want to save the file and then open it manually.
public static byte[] GetBytesFromStream(Stream input){
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream()){
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0){
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
public void OnButtonClick(){
var templateUri = new Uri("/Common/New.xlsx, UriKind.Relative");
var templateStream = Application.GetResourceStream(templateUri).Stream;
var bytes = GetBytesFromStream(templateStream);
var sfd = new SaveFileDialog() {
DefaultExt = "xlsx",
Filter = "Excel Files (*.xlsx)|*.xlsx|All files(*.*)|*.*",
FilterIndex = 1
};
if (sfd.ShowDialog() == true) {
using (Stream stream = sfd.OpenFile()) {
stream.Write(bytes, 0, bytes.Length);
}
}
}
You can have the file stored server side and when the user clicks the button you tell the browser to get he file in question. The browser will then take over and ask the user if they want to save the file to disk or open using a known application.
public void OnButtonClick(){
string link = "{the url/endpoint to the file on the server}";
System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(link), "_blank");
}
You can go down the AutomationFactory route but that would require alot of configuration changes like suggested here
I think it's much better to have such things on the server rather than on the client side. The server is more well equipped to handle such processing.
Try the following:
var TemplateUri = new Uri("/Common/New.xlsx, UriKind.Relative");
var stream = Application.GetResourceStream(sheetUri).Stream;
The file is deployed witin the xap file (which is a zip file) and cannot be handled by a normal file on the disk.
It is not clear for me what Excel library you are using, but it should allow you to load data from Stream.
I want to open a file which is saved in my local directory folder in asp.net c#.
I have tried filestream like this:
path = TreeView1.SelectedNode.Value.ToString(); // file path (D:\projects\Content\Media\xxxx.PDF )
if (IsPostBack)
{
path = TreeView1.SelectedNode.Value.ToString();
FileInfo fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fileStream);
}
}
As per my understanding of your question you are trying open the file means you are trying to launch the file
If i am right use this
System.Diagnostics.Process.Start(#"Your_PDF_File_Path");
Edit:Here is an easy option for displaying pdf file in html5.
<embed src="Your_File.pdf" width="800px" height="2100px">
I am using iTextSharp in my MVC application to create a .pdf file, but is there a way to convert it to a .doc file?
public ActionResult Download(int? Id)
{
string FileName = "Test";
var FilePath = Path.Combine(Path.GetTempPath(), "Temp.pdf");
Document UserPDF = new Document();
PdfWriter.GetInstance(UserPDF, new FileStream(FilePath, FileMode.Create));
CreateCv(UserPDF); // This is where the PDF is created
var fs = new FileStream(FilePath, FileMode.Open);
var Bytes = new byte[fs.Length];
fs.Read(Bytes, 0, (int)fs.Length);
fs.Close();
return File(Bytes, "application/pdf", FileName + ".pdf");
}
To put it simply, no. There is no way to convert it to a DOC file using iTextSharp. It only supports the reading and generating of PDF files.
Converting PDF to DOC is possible by using some other third party libraries but there is no solid way of doing it (and preserving formatting / whitespace) at the moment. If you search the web, people suggest creating an image from the PDF and then appending the image to the end of a blank DOC file (which is a major hack).