Is there a wmv writer in vtk? - c#

I am recording a video using vtkAVIWriter which writes .avi file, Is there a way to generate .wmv file using other writer, I have searched but did not find any suitable writer for wmv format.
here is code to generate .avi file
private void WriteAVIFile(RenderWindowControl renderWindowControl, string fileName)
{
using (var movieWriter = vtkAVIWriter.New())
{
var imageFilter = vtkWindowToImageFilter.New();
imageFilter.SetInput(renderWindowControl.RenderWindow);
imageFilter.Update();
movieWriter.SetInputConnection(imageFilter.GetOutputPort());
movieWriter.SetQuality(2);
movieWriter.SetRate(4);
movieWriter.SetFileName(fileName + ".avi");
movieWriter.Update();
movieWriter.Start();
//perform some action
var renderer = renderWindowControl.RenderWindow.GetRenderers().GetFirstRenderer();
var camera = renderer.GetActiveCamera();
for (int i = 1; i <= 100; i++)
{
camera.Roll(i);
renderer.GetRenderWindow().Render();
imageFilter.Modified();
imageFilter.Update();
movieWriter.Write();
}
movieWriter.End();
}
}

Related

How to extract all pages and attachments from PDF to PNG

I am trying to create a process in .NET to convert a PDF and all it's pages + attachments to PNGs. I am evaluating libraries and came across PDFiumSharp but it is not working for me. Here is my code:
string Inputfile = "input.pdf";
string OutputFolder = "Output";
string fileName = Path.GetFileNameWithoutExtension(Inputfile);
using (PdfDocument doc = new PdfDocument(Inputfile))
{
for (int i = 0; i < doc.Pages.Count; i++)
{
var page = doc.Pages[i];
using (var bitmap = new PDFiumBitmap((int)page.Width, (int)page.Height, false))
{
page.Render(bitmap);
var targetFile = Path.Combine(OutputFolder, fileName + "_" + i + ".png");
bitmap.Save(targetFile);
}
}
}
When I run this code, I get this exception:
screenshot of exception
Does anyone know how to fix this? Also does PDFiumSharp support extracting PDF attachments? If not, does anyone have any other ideas on how to achieve my goal?
PDFium does not look like it supports extracting PDF attachments. If you want to achieve your goal, then you can take a look at another library that supports both extracting PDF attachments as well as converting PDFs to PNGs.
I am an employee of the LEADTOOLS PDF SDK which you can try out via these 2 nuget packages:
https://www.nuget.org/packages/Leadtools.Pdf/
https://www.nuget.org/packages/Leadtools.Document.Sdk/
Here is some code that will convert a PDF + all attachments in the PDF to separate PNGs in an output directory:
SetLicense();
cache = new FileCache { CacheDirectory = "cache" };
List<LEADDocument> documents = new List<LEADDocument>();
if (!Directory.Exists(OutputDir))
Directory.CreateDirectory(OutputDir);
using var document = DocumentFactory.LoadFromFile("attachments.pdf", new LoadDocumentOptions { Cache = cache, LoadAttachmentsMode = DocumentLoadAttachmentsMode.AsAttachments });
if (document.Pages.Count > 0)
documents.Add(document);
foreach (var attachment in document.Attachments)
documents.Add(document.LoadDocumentAttachment(new LoadAttachmentOptions { AttachmentNumber = attachment.AttachmentNumber }));
ConvertDocuments(documents, RasterImageFormat.Png);
And the ConvertDocuments method:
static void ConvertDocuments(IEnumerable<LEADDocument> documents, RasterImageFormat imageFormat)
{
using var converter = new DocumentConverter();
using var ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD);
ocrEngine.Startup(null, null, null, null);
converter.SetOcrEngineInstance(ocrEngine, false);
converter.SetDocumentWriterInstance(new DocumentWriter());
foreach (var document in documents)
{
var name = string.IsNullOrEmpty(document.Name) ? "Attachment" : document.Name;
string outputFile = Path.Combine(OutputDir, $"{name}.{RasterCodecs.GetExtension(imageFormat)}");
int count = 1;
while (File.Exists(outputFile))
outputFile = Path.Combine(OutputDir, $"{name}({count++}).{RasterCodecs.GetExtension(imageFormat)}");
var jobData = new DocumentConverterJobData
{
Document = document,
Cache = cache,
DocumentFormat = DocumentFormat.User,
RasterImageFormat = imageFormat,
RasterImageBitsPerPixel = 0,
OutputDocumentFileName = outputFile,
};
var job = converter.Jobs.CreateJob(jobData);
converter.Jobs.RunJob(job);
}
}

Extract Image and its name from pdf using iTextSharp

I am using iTextSharp c# to extract images and its name from catalog pdf. I Am able to extract images from pdf, but struggling with extracting its corresponding image name as per the attached screenshot and save the file with that name. Please find the code below and let me know your suggestions.
Sample PDF: https://docdro.id/PwBsNR9
Code:
private static List<System.Drawing.Image> ExtractImages(String PDFSourcePath)
{
List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();
iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
iTextSharp.text.pdf.PdfObject PDFObj = null;
iTextSharp.text.pdf.PdfStream PDFStremObj = null;
try
{
RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath);
PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);
for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
{
PDFObj = PDFReaderObj.GetPdfObject(i);
if ((PDFObj != null) && PDFObj.IsStream())
{
PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);
if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
{
}
if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
{
try
{
iTextSharp.text.pdf.parser.PdfImageObject PdfImageObj =
new iTextSharp.text.pdf.parser.PdfImageObject((iTextSharp.text.pdf.PRStream)PDFStremObj);
System.Drawing.Image ImgPDF = PdfImageObj.GetDrawingImage();
ImgList.Add(ImgPDF);
}
catch (Exception)
{
}
}
}
}
PDFReaderObj.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ImgList;
}
Unfortunately the example PDF is not tagged. Thus, one has to otherwise try and associate title text and image, either by analyzing the location in respect to each other or by exploiting a pattern in the content streams.
In the case at hand analyzing the location in respect to each other is feasible as the title always is (at least partially) drawn on the matching image or is the text right beneath it. Thus, one could in a first pass extract the text with position from a page and in a second one the images, at the same time looking for a title in the previously extracted text in the image area or right beneath. Alternatively one could first extract images with position and size and then extract the text in these areas.
But there also is a certain pattern in the content streams: The titel is always drawn in a single text drawing instruction right after the corresponding image is drawn. Thus, one can also go ahead and in one pass extract images and the next drawn text as associated title.
Either approach can be implemented using the iText parser API. For example in case of the latter approach as follows: first, one implements a render listener that behaves as described, i.e. saves images and the following text:
internal class ImageWithTitleRenderListener : IRenderListener
{
int imageNumber = 0;
String format;
bool expectingTitle = false;
public ImageWithTitleRenderListener(String format)
{
this.format = format;
}
public void BeginTextBlock()
{ }
public void EndTextBlock()
{ }
public void RenderText(TextRenderInfo renderInfo)
{
if (expectingTitle)
{
expectingTitle = false;
File.WriteAllText(string.Format(format, imageNumber, "txt"), renderInfo.GetText());
}
}
public void RenderImage(ImageRenderInfo renderInfo)
{
imageNumber++;
expectingTitle = true;
PdfImageObject imageObject = renderInfo.GetImage();
if (imageObject == null)
{
Console.WriteLine("Image {0} could not be read.", imageNumber);
}
else
{
File.WriteAllBytes(string.Format(format, imageNumber, imageObject.GetFileType()), imageObject.GetImageAsBytes());
}
}
}
Then one parses the document pages using that render listener:
using (PdfReader reader = new PdfReader(#"EVERMOTION ARCHMODELS VOL.78.pdf"))
{
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
ImageWithTitleRenderListener listener = new ImageWithTitleRenderListener(#"EVERMOTION ARCHMODELS VOL.78-{0:D3}.{1}");
for (var i = 1; i <= reader.NumberOfPages; i++)
{
parser.ProcessContent(i, listener);
}
}
I hope this would help.
I am doing this type of thing but if this would help.
// existing pdf path
PdfReader reader = new PdfReader(path);
PRStream pst;
PdfImageObject pio;
PdfObject po;
// number of objects in pdf document
int n = reader.XrefSize;
//FileStream fs = null;
// set image file location
//String path = "E:/";
for (int i = 0; i < n; i++)
{
// get the object at the index i in the objects collection
po = reader.GetPdfObject(i);
// object not found so continue
if (po == null || !po.IsStream())
continue;
//cast object to stream
pst = (PRStream)po;
//get the object type
PdfObject type = pst.Get(PdfName.SUBTYPE);
//check if the object is the image type object
if (type != null && type.ToString().Equals(PdfName.IMAGE.ToString()))
{
//get the image
pio = new PdfImageObject(pst);
// fs = new FileStream(path + "image" + i + ".jpg", FileMode.Create);
//read bytes of image in to an array
byte[] imgdata = pio.GetImageAsBytes();
try
{
Stream stream = new MemoryStream(imgdata);
FileStream fs = stream as FileStream;
if (fs != null) Console.WriteLine(fs.Name);
}
catch
{
}
}
}
Now you can save your stream.
public void SaveStreamToFile(string fileFullPath, Stream stream)
{
if (stream.Length == 0) return;
// Create a FileStream object to write a stream to a file
using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
{
// Fill the bytes[] array with the stream data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}

Save PDF document to the Response.OutputStream using PDFsharp

I'm trying to save a copy of the source file directly into a response output stream. But, as a result of this code, the browser window has a dark background. How can I do it without using а MemoryStream?
public static void CreateCollage(IEnumerable<Stamp> stamps, Stream input)
{
using (PdfDocument outDoc = new PdfDocument())
using (PdfDocument inputDoc = PdfReader.Open(input, PdfDocumentOpenMode.Import))
{
for (int i = 0; i < inputDoc.PageCount; i++)
{
var page = inputDoc.Pages[i];
var pageOut = outDoc.AddPage(page);
foreach (var stamp in stamps.Where(s => s.xyp.page == (i + 1)))
InsertData(pageOut, stamp, page.Width.Value, page.Height.Value);
}
outDoc.Save(context.Response.OutputStream, true);
}
}
If I use Save() function - I get an error:
The specified method is not supported.
in System.Web.HttpResponseStream.get_Position()
in PdfSharp.Pdf.IO.PdfWriter.WriteFileHeader(PdfDocument document)
in d:\Users\yudina\Desktop\pdfsharp\PDFsharp\src\PdfSharp\Pdf.IO\PdfWriter.cs:row 488
You do not call outDoc.Close() and nothing ever gets written into your OutputStream.

AcmNotPossible calling acmStreamOpen Error

In my application i have some Audio files those are in .wav Format, Here i am checking Each audio file BitRate , and if any file in below 128Kbps,i changed those files bit rate to 128kbps,by using Below code
int bitrate;
string FullPath = #Server.MapPath("~/AudioFiles/");
string[] filePaths = Directory.GetFiles(FullPath, "*.wav", SearchOption.AllDirectories);
for (int i = 0; i < filePaths.Length; i++)
{
string[] FileExt = filePaths[i].Split('\\');
string[] Ext = FileExt[FileExt.Length - 1].Split('.');
string ExtFile = Ext[Ext.Length - 1];
if (ExtFile == "wav" || ExtFile == "WAV")
{
using (var reader = new WaveFileReader(filePaths[i]))
{
bitrate = reader.WaveFormat.AverageBytesPerSecond * 8;
reader.Dispose();
}
if (bitrate < 128000)
{
using (var reader = new WaveFileReader(filePaths[i]))
{
var newFormat = new WaveFormat(8000, 16, 1);
using (var conversionStream = new WaveFormatConversionStream(newFormat, reader))
{
WaveFileWriter.CreateWaveFile(Server.MapPath("~/AudioFiles/" + FileExt[FileExt.Length - 1]), conversionStream);
}
}
}
}
the above code is working for most of the files, But i get below error for some audio files.
how can i solve the issue?
You can typically only change one thing at a time with ACM, so if you have a 16kHz stereo file, you can't go to an 8kHz mono file in one go.
So you need to see what WaveFormat your WaveFileReader has, and possibly do multiple conversion steps.
It may also be that your input WAV file is using a codec that ACM can't decode. But again you'd need to examine your input WaveFormat to know that.

How to import a 3D object from one PDF to another using iTextSharp

I'm using iTextSharp 5.5 to construct PDF documents. The documents start with text information and end with imported JPEG images and multi-page PDF files. Some of the PDFs contain annotations, specifically 3D models.
Edit (3/21/2014): Here is a complete, simplified example that illustrates what I'm trying to accomplish, and where the error occurs in AddPdf().
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace PdfTest
{
class Program
{
private const string path = "w:\\tmp\\pdf";
static void Main(string[] args)
{
using (var ms = new MemoryStream())
{
var document = new Document(PageSize.LETTER, 40, 40, 30, 30);
var writer = PdfWriter.GetInstance(document, ms); // Without this, I get a zero-length file
document.Open();
AddText(document, "TEST");
AddImage(document, Path.Combine(path, "import1.jpg"));
AddPdf(document, ms, Path.Combine(path, "import2.pdf"));
document.Close();
File.WriteAllBytes(Path.Combine(path, "test.pdf"), ms.ToArray());
}
}
private static void AddText(Document document, string text)
{
document.Add(new Paragraph(text, FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12f)));
}
private static void AddImage(Document document, string sourcePath)
{
var pic = Image.GetInstance(sourcePath);
var maxWidth = document.PageSize.Width - 72f;
var maxHeight = document.PageSize.Height - 150f;
if (pic.Width > maxWidth || pic.Height > maxHeight)
{
pic.ScaleToFit(maxWidth, maxHeight);
}
document.NewPage();
document.Add(pic);
}
private static void AddPdf(Document document, Stream stream, string sourcePath)
{
var copy = new PdfCopy(document, stream);
// Read the source PDF
var reader = new PdfReader(sourcePath);
var pageCount = reader.NumberOfPages;
// Import each page
for (var i = 0; i < pageCount; i++)
{
var pageNum = i + 1;
document.SetPageSize(reader.GetPageSizeWithRotation(pageNum));
document.NewPage(); // <--- "Document is not open" error here
var page = copy.GetImportedPage(reader, pageNum);
copy.AddPage(page);
}
}
}
}
What is the correct way to construct a document by adding elements and imported pages?

Categories