I’m searching for quite a while how to print “PDF” files in c# ,
I’m trying to print shipping labels which I get it in a “GZip Stream” string and the format is a pdf,
So my question is what’s is the best way to print out the “PDF” label (Not images or any image format), and also be able to set to which printer to print?
The best way would be without having to save the label in my computer and then recall the file!
it's doesn't make sense that the only way is to install third party classes!
This is what i have done!
private void PrintFDFLabel(string imageLabel)
{
var byteStream = Convert.FromBase64String(imageLabel);
MemoryStream memoryStream = Decompress(byteStream);// i need to Decompress the Gzip
PrintDocument print = new PrintDocument();
print.PrinterSettings.PrinterName = Properties.Settings.Default.DefaultPrimePrinter;
print.Print();
}
private MemoryStream Decompress(byte[] b)
{
MemoryStream memoryStream;
using (var ms = new MemoryStream())
{
using (var bs = new MemoryStream(b))
using (GZipStream gZipStream = new GZipStream(bs, CompressionMode.Decompress))
{
memoryStream = new MemoryStream();
gZipStream.CopyTo(memoryStream);
}
return memoryStream;
}
}
Related
I'm using c# and asp core 3 and have this right now.
string templatePath = Path.Combine(_webHostEnvironment.WebRootPath, #"templates\pdf\test.pdf");
Stream finalStream = new MemoryStream();
foreach (Info p in list)
{
Stream pdfInputStream = new FileStream(path: templatePath, mode: FileMode.Open);
Stream outStream = PdfService.FillForm(pdfInputStream, p);
outStream.Position = 0;
outStream.CopyTo(finalStream);
outStream.Dispose();
pdfInputStream.Dispose();
}
finalStream.Position = 0;
return File(finalStream, "application/pdf", "test.pdf"));
Right now I just get the first PDF when there should be 3. How to combine all the streams (PDF) created in the loop into 1 PDF? I'm using iTextSharp and using this as a guide to produce the FillForm code.
https://medium.com/#taithienbo/fill-out-a-pdf-form-using-itextsharp-for-net-core-4b323cb58459
You can't just combine PDF by adding them into a single stream :-)
You can add each PDF stream to an array and request ITextSharp to combine them and after that returning the newly created stream.
List<Stream> pdfStreams = new List<Stream>();
foreach(var item in list)
{
// Open PDF + fill form
pdfStreams.Add(outstream);
}
var newStream = Merge(pdfStreams);
return File(newStream)
I don't know ITextSharp but it seems you can merge PDFs : https://weblogs.sqlteam.com/mladenp/2014/01/10/simple-merging-of-pdf-documents-with-itextsharp-5-4-5/
Edit
By the way, you could use "using" statement for stream (you wouldn't have to call dispose yourself) and I don't know how heavy are your PDFs but you should maybe consider to use the ".CopyToAsync".
I'm using the DryWetMidi library to process some MIDI data.
First I get the MIDI Data as a MemoryStream from the Clipboard:
MemoryStream ms = (MemoryStream)Clipboard.GetDataObject().GetData("Standard MIDI File");
MidiFile mid = MidiFile.Read(ms);
Then I do some stuff with the midi:
mid.RemoveNotes(n => n.NoteName == NoteName.FSharp);
Now I want to write it back to the Clipboard. I managed to do this like this:
using (FileStream file = new FileStream("file.mid", FileMode.Create, FileAccess.
{
mid.Write(file);
}
using (MemoryStream ms2 = new MemoryStream())
using (FileStream file = new FileStream("file.mid", FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms2.Write(bytes, 0, (int)file.Length);
Clipboard.Clear();
Clipboard.SetData(midiFormat, ms2);
}
File.Delete("file.mid");
As you can see, first I write the MIDI to a file, then I read that file into a MemoryStream which I then write into the Clipboard. This makes not much sense, because it would be simpler to write it to a MemoryStream directly. Also, I don't want to write a file to the users file system. But there's the problem. I tried it like this:
using (MemoryStream ms2 = new MemoryStream())
{
mid.Write(ms2);
}
This doesn't give me an error, but the MemoryStream is completely empty. Calling ms2.Length results in a System.ObjectDisposedException.
How can I write the midi directly into the MemoryStream?
EDIT: Here's the link to the DryWetMidi Write() Method.
Second Edit: Here's a piece of code that won't work:
MemoryStream ms = (MemoryStream)Clipboard.GetDataObject().GetData(midiFormat);
MidiFile mid = MidiFile.Read(ms);
mid.RemoveNotes(n => n.NoteName == NoteName.FSharp);
MemoryStream ms2 = new MemoryStream();
mid.Write(ms2);
var T = ms2.Length; //This will throw an exception
Third Edit: I am 100% sure that the code posted is exactly the same I'm running. Here's the StackTrace. (Gist because formatting was terrible on SO).
As far as I can see, DryWetMidi uses BinaryWriter to write to stream. And the default behaviour of BinaryWriter is that when it is disposed, It'll dispose the stream as well.
You can't read from MemoryStream when it's disposed but you can call ToArray().
byte[] result;
using (MemoryStream ms2 = new MemoryStream())
{
mid.Write(ms2);
result = ms2.ToArray();
}
I have a function that add an Image file to stream like this:
//sourceImage is a url for an image
public Stream AddImageToStream(string sourceImage)
{
try
{
using (WebClient webClient = new WebClient())
{
byte[] data = webClient.DownloadData(sourceImage);
using (MemoryStream mem = new MemoryStream(data))
{
using (var yourImage = Image.FromStream(mem))
{
Image img = yourImage;
var ms = img.ToStream(ImageFormat.Png);
img.Dispose();
return ms;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
I can't find Video class in C#.
How can implement this function for video files?
Basically you already know how to turn the downloaded content into a MemoryStream:
public Stream DownloadToStream(string url)
{
using (var webClient = new System.Net.WebClient())
{
byte[] data = webClient.DownloadData(url);
var ms = new System.IO.MemoryStream(data);
return ms;
}
}
But this will need the video or whatever to fit into memory, there is no progress handling and nothing asynchronous. Also you should Dispose() the returned stream when you finished your operations with it.
There is no Video class in the basic .NET framework as videos are a complex topic. If you want to process it, you should look into some of the frameworks/libraries for that and definitely have to learn about asynchronous processing and streams.
Update: If you can use current versions of the framework you might be interested in using HttpClient.GetStreamAsync. This will not consume all your memory. Still if you want to edit the video data you will require a framework specialized on video editing.
My PDF is not readable after tried to edit the text.
How to make it works ?
my error message :
Adobe Reader could not open '495049.pdf' because it is either not a supported file type or because the file has been damaged (for example, it was sent as email attachment and wasn't correctly decoded)
Basically the objective is to edit PDF doc and replace particular text.
Input already in binary stream (byte[ ])
I worked on C# environment & iText for the PDF editing lib.
Here's my piece of code :
using (PdfReader reader = new PdfReader(doc.FileStream))
{
PdfDictionary dict = reader.GetPageN(1);
PdfObject pdfObject = dict.GetDirectObject(PdfName.CONTENTS);
if (pdfObject.IsStream())
{
PRStream stream = (PRStream)pdfObject;
byte[] data = PdfReader.GetStreamBytes(stream);
stream.SetData(System.Text.Encoding.ASCII.GetBytes(System.Text.Encoding.ASCII.GetString(data).Replace("[ReplacmentText]", "Hello World")));
}
using (MemoryStream ms = new MemoryStream())
{
var ignored = new PdfStamper(reader, ms);
reader.Close();
return ms.ToArray();
}
}
Your main mistake is that you retrieve the contents of the memory stream before closing the stamper; actually you don't close it at all!
Only when closing the stamper, the final part of the PDF is written. Thus:
using (MemoryStream ms = new MemoryStream())
{
var ignored = new PdfStamper(reader, ms);
ignored.Close();
reader.Close();
return ms.ToArray();
}
Your other problem (probably not relevant for your current test documents but in general):
stream.SetData(System.Text.Encoding.ASCII.GetBytes(System.Text.Encoding.ASCII.GetString(data).Replace("[ReplacmentText]", "Hello World")));
This assumes very much, especially that the stream content only contains ASCII bytes, that the place holder "[ReplacementText]" (I assume this is the correct spelling) occurs in one piece and in the immediate content streams, that the font used to draw the place holder and its replacement uses an ASCII'ish encoding, and that this font has glyphs for all characters in "Hello World". Neither of these assumptions are automatically true.
I want to convert mp3 files to WAV. In DirectX.DirectSound the secondary buffer is supporting only WAV. I am converting the files using naudio and this is working fine.
using (Mp3FileReader reader = new Mp3FileReader(mp3File))
{
WaveFileWriter.CreateWaveFile(outputFile, reader);
}
The problem is that I can't save the files on disk so I have to use them with stream.
Mp3FileReader mp3reader = new Mp3FileReader(filenamePathMp3);
var stream=WaveFormatConversionStream.CreatePcmStream(mp3reader);
which throws an exception Value does not fall within the expected range. How Can I make a stream with the audio converted to WAV or Raw audio for the secondaryBuffer without writing on disk?
Thank you in advance,
WaveFileWriter can write to a Stream instead of a file so you can just pass in a MemoryStream. Also, Mp3FileReader.Read already returns PCM so you could read out into a byte[] and then insert that into your memory stream if you prefer.
I've achieved to convert MP3 to WAV without writing it to the disk by using MemoryStream and WaveFileWriter.WriteWavFileToStream
You can also set up sampleRate bitrate and channel using RawSourceWaveStream
public static byte[] ConvertMp3ToWav(byte[] mp3File)
{
using (var retMs = new MemoryStream())
using (var ms = new MemoryStream(mp3File))
using (Mp3FileReader reader = new Mp3FileReader(ms))
{
var rs = new RawSourceWaveStream(reader, new WaveFormat(16000, 1));
using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(rs))
{
WaveFileWriter.WriteWavFileToStream(retMs,pcmStream);
return retMs.ToArray();
}
}
}