Cross reference table or cross reference stream not found in AddImage function - aspose

I'm new to Aspose PDF. I don't understand why I'm getting this cross reference error. This happens when the image is being added to the pdf file.
Below is the code sample.
// Gets the image file to be merged with the document
var b1 = GetDocumentFile(imageLayer.UNIQUE_ID);
if (b1.File.DocumentLayer?.PAGE_NUMBER != null)
{
var i = b1.File.DocumentLayer.PAGE_NUMBER.Value;
var pngBin = EFSUtil.ReadFileFromFileServer(b1.File.FullFilePathAndName, b1.Server);
pngBin = CheckIfWebPAndProcess(pngBin);
//open document based ont eh stream
var pdfDocument = new Document(pdfMemoryStream);
var rect = pdfDocument.Pages[i].GetPageRect(true);
pdfDocument.Pages[i].AddImage(new MemoryStream(pngBin), rect); <-- Error hit here
var bMemStrm = new MemoryStream();
pdfDocument.Save(bMemStrm);
pdfMemoryStream = bMemStrm;
}
I tried to get some valuable information as to why the error happened during the AddImage() and I also tried to understand why the error happened and how to resolve it but was unsuccessful. The nearest that I could look for are these links.
Manipulate Images
Page class
I hope you can help me with this. Thank you
UPDATE
Not sure if this would help, but here's the stacktrace when the issue occurred in the AddImage
at   .   ​()
at   .(Int32 , Int32& )
at   .   ​(Int32 )
at ​  .(Int32 )
at Aspose.Pdf.OperatorCollection.79au5vc3bv4m9r8vf6tce224vh3rwyeh ​()
at Aspose.Pdf.OperatorCollection.(IList )
at Aspose.Pdf.OperatorCollection.(IList , )
at Aspose.Pdf.OperatorCollection.(List`1 )
at Aspose.Pdf.OperatorCollection.Add(ICollection ops)
at Aspose.Pdf.Page.(Stream , Rectangle , Matrix , CompositingParameters , Boolean , Boolean ,   & )
at Aspose.Pdf.Page.(Stream , Rectangle , Matrix , CompositingParameters ,   & )
at Aspose.Pdf.Page.AddImage(Stream imageStream, Rectangle imageRect)

I found out that my PDF did have problems. I was able to validate this through this link
3-HEIGHTS™ PDF VALIDATOR ONLINE TOOL

Related

Aspose.Barcode cannot read DecodeType.Code128 barcode

The aspose.barcode reader is unable to read the barcode of type DecodeType.Code128
Workflow Steps
1>Using Aspose.Barcode we have created a barcode using DecodeType.Code128 and put on PDF page ( our clients use this page as separator sheet)
2>Our client then insert this barcode page between several physical documents and scanned them all, which creates big single PDF
3>Our splitting process then, loop through all pages and check if any page is barcode page, and splits the big PDF into individual small PDF
Issue is some times the scanned quality of the barcode is not that great, and in such case ASPOSE.Barcode unable to read the barcode.
I have attached couple of barcode PDF with low scanned quality, and aspose is not able to read these barcodes. I have tried different combinations of RecognitionMode and ManualHints options without any luck
Below is my code to identity barcode page
using (var fs = new FileStream(file, FileMode.Open))
{
var pdfDocument = new Document(fs);
foreach (Page page in pdfDocument.Pages)
{
var isSeparator = splitter.IsSeparator(page);
Assert.IsTrue(isSeparator);
}
}
public bool IsSeparator(Page page)
{
if (page.Resources.Images != null && page.Resources.Images.Count >= 1)
{
var img = page.Resources.Images[1];
using (MemoryStream barcodeImage = new MemoryStream())
{
img.Save(barcodeImage, ImageFormat.Jpeg);
barcodeImage.Seek(0L, SeekOrigin.Begin);
using (BarCodeReader barcodeReader = new BarCodeReader(barcodeImage, _barcodeDecodeType))
{
barcodeReader.RecognitionMode = RecognitionMode.MaxQuality;
while (barcodeReader.Read())
{
var barcodeText = barcodeReader.GetCodeText();
if (barcodeText.ToLower() == "eof")
{
return true;
}
}
}
}
}
return false;
}
Unable to reproduce the issue at my end. I used the following sample code snippet to recognize the barcode along with latest version of the API. It is always recommended to use the latest version of the API as it contains new features and improvements.
CODE:
Aspose.Pdf.License licensePdf = new Aspose.Pdf.License();
licensePdf.SetLicense(#"Aspose.Total.lic");
// bind the pdf document
Aspose.Pdf.Facades.PdfExtractor pdfExtractor = new Aspose.Pdf.Facades.PdfExtractor();
pdfExtractor.BindPdf(#"173483_2.pdf");
// extract the images
pdfExtractor.ExtractImage();
// save images to stream in a loop
while (pdfExtractor.HasNextImage())
{
// save image to stream
System.IO.MemoryStream imageStream = new System.IO.MemoryStream();
pdfExtractor.GetNextImage(imageStream);
imageStream.Position = 0;
Aspose.BarCode.BarCodeRecognition.BarCodeReader barcodeReader =
new Aspose.BarCode.BarCodeRecognition.BarCodeReader(imageStream);
while (barcodeReader.Read())
{
Console.WriteLine("Codetext found: " + barcodeReader.GetCodeText() + ", Symbology: " + barcodeReader.GetCodeType().ToString());
}
// close the reader
barcodeReader.Close();
}
Further to update you that the same query has been post on Aspose.BarCode support forum. You may please visit the link for details.
I work as developer evangelist at Aspose.

How to display Highlighted text using Solrj

I am new to Solr and SolrJ. I am trying to use for a desktop application and I have files(text files) to index and search. I wanted to use highlight feature and display the fragments with highlight,but I don't get them to display in yellow background as you highlight a text, please let me know how to display the text in yellow background.
here is my code snippet:
public void TestHighLight(SolrQuery query) throws
SolrServerException, IOException {
query.setQuery("*");
query.set("hl", "true");
query.set("hl.snippets", "5");
query.set("q", "text:Pune");
query.set("hl.fl", "*");
QueryResponse queryResponse = client.query(query);
SolrDocumentList docs = queryResponse.getResults();
Iterator iter = docs.iterator();
for (int i = 0; i < docs.size(); i++) {
iter = docs.get(i).getFieldNames().iterator();
String fldVal = (String) docs.get(i).getFieldValue("id");
String docID = (String) docs.get(i).get("id");
while (iter.hasNext()) {
String highlighText = getHighlightedText(queryResponse,
"text", docID);
System.out.println(" tHighlightedText is " + highlighText );
}
}
}
The output looks like this:how do I color it ?
[ for Java Developer at Pune
Thanks a lot !
Set the pre and post parameters of the highlighter. Specifies the “tag” to use before a highlighted term. This can be any string, but is most often an HTML or XML tag.
e.g:
solrQueryHandler.setHighlightSimplePre("<font color="yellow">");
solrQueryHandler.setHighlightSimplePost("/font");
But note that this will work only for the Original Highlighter

How do you capture current frame from a MediaElement in WinRT (8.1)?

I am trying to implement a screenshot functionality in a WinRT app that shows Video via a MediaElement. I have the following code, it saves a screenshot that's the size of the MediaElement but the image is empty (completely black). Tried with various types of Media files. If I do a Win Key + Vol Down on Surface RT, the screen shot includes the Media frame content, but if I use the following code, it's blackness all around :(
private async Task SaveCurrentFrame()
{
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(Player);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
MultimediaItem currentItem = (MultimediaItem)this.DefaultViewModel["Group"];
StorageFolder currentFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
var saveFile = await currentFolder.CreateFileAsync(currentItem.UniqueId + ".png", CreationCollisionOption.ReplaceExisting);
if (saveFile == null)
return;
// Encode the image to the selected file on disk
using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
DisplayInformation.GetForCurrentView().LogicalDpi,
DisplayInformation.GetForCurrentView().LogicalDpi,
pixelBuffer.ToArray());
await encoder.FlushAsync();
}
}
Here MultimediaItem is my View Model class that among other things has a UniqueId property that's a string.
'Player' is the name of the Media Element.
Is there anything wrong with the code or this approach is wrong and I've to get in the trenches with C++?
P.S. I am interested in the WinRT API only.
Update 1 Looks like RenderTargetBitmap doesn't support this, the MSDN documentation clarifies it http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.rendertargetbitmap .
I'll appreciate any pointers on how to do it using DirectX C++. This is a major task for me so I'll crack this one way or the other and report back with the solution.
Yes, it is possible - little bit tricky, but working well.
You dont use mediaElement, but StorageFile itself.
You need to create writableBitmap with help of Windows.Media.Editing namespace.
Works in UWP (Windows 10)
This is complete example with file picking and getting video resolution and saving image to Picture Library
TimeSpan timeOfFrame = new TimeSpan(0, 0, 1);//one sec
//pick mp4 file
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
picker.FileTypeFilter.Add(".mp4");
StorageFile pickedFile = await picker.PickSingleFileAsync();
if (pickedFile == null)
{
return;
}
///
//Get video resolution
List<string> encodingPropertiesToRetrieve = new List<string>();
encodingPropertiesToRetrieve.Add("System.Video.FrameHeight");
encodingPropertiesToRetrieve.Add("System.Video.FrameWidth");
IDictionary<string, object> encodingProperties = await pickedFile.Properties.RetrievePropertiesAsync(encodingPropertiesToRetrieve);
uint frameHeight = (uint)encodingProperties["System.Video.FrameHeight"];
uint frameWidth = (uint)encodingProperties["System.Video.FrameWidth"];
///
//Use Windows.Media.Editing to get ImageStream
var clip = await MediaClip.CreateFromFileAsync(pickedFile);
var composition = new MediaComposition();
composition.Clips.Add(clip);
var imageStream = await composition.GetThumbnailAsync(timeOfFrame, (int)frameWidth, (int)frameHeight, VideoFramePrecision.NearestFrame);
///
//generate bitmap
var writableBitmap = new WriteableBitmap((int)frameWidth, (int)frameHeight);
writableBitmap.SetSource(imageStream);
//generate some random name for file in PicturesLibrary
var saveAsTarget = await KnownFolders.PicturesLibrary.CreateFileAsync("IMG" + Guid.NewGuid().ToString().Substring(0, 4) + ".jpg");
//get stream from bitmap
Stream stream = writableBitmap.PixelBuffer.AsStream();
byte[] pixels = new byte[(uint)stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
using (var writeStream = await saveAsTarget.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, writeStream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)writableBitmap.PixelWidth,
(uint)writableBitmap.PixelHeight,
96,
96,
pixels);
await encoder.FlushAsync();
using (var outputStream = writeStream.GetOutputStreamAt(0))
{
await outputStream.FlushAsync();
}
}
Yeah...I spent lot of hours by this
Ok I have managed to get making snapshot from MediaElement on button press to work.
I am passing MediaStreamSource object to MediaElement using SetMediaStreamSource method. MediaStreamSource has event SampleRequested which is fired basicly everytime new frame is drawn. Then using boolean I control when to create bitmap
private async void MediaStream_SampleRequested(MediaStreamSource sender, MediaStreamSourceSampleRequestedEventArgs args)
{
if (!takeSnapshot)
{
return;
}
takeSnapshot = false;
Task.Run(() => DecodeAndSaveVideoFrame(args.Request.Sample));
}
After that what is left is to decode compressed image and convert it to WriteableBitmap. The image is (or at least was in my case) in YUV fromat. You can get the byte array using
byte[] yvuArray = sample.Buffer.ToArray();
and then get data from this array and convert it to RGB. Unfortunetly I cannot post entire code but I'm gonna give you a few more hints:
YUV to RGB wiki here you have wiki describing how does YUV to RGB conversion works.
Here I found python project which solution I have adapted (and works perfectly). To be more precise you have to analize how method NV12Converter works.
The last thing is to change takeSnapshot boolean to true after pressing button or doing other activity :).

Capturing Snap from Camera using Win RT

I am Wrting code to capture image from camera.Below is the code I have written.
Here method CapturePhotoToStorageFileAsync doesnot return.
auto MediaCap = ref new Windows::Media::Capture::MediaCapture();
auto ImageProp = ref new Windows::Media::Capture::ImageEncodingProperties ();
ImageProp->Height = 240;
ImageProp->Width = 320;
ImageProp->Subtype = "JPEG";
Windows::Storage::StorageFile^ strFile;
auto res = MediaCap->CapturePhotoToStorageFileAsync(ImageProp,strFile);
res->Completed = ref new AsyncActionCompletedHandler([](IAsyncAction ^action)
{
//action->GetResults();
//action->Start();
///action->Close();
});
res->Start();
Am I missing something here??
Did you want to show UI to the user or just silently capture? The only C++ camera sample I've found uses CameraCaptureUI and CaptureFileAsync - then the operation is getting a StorageFile^ back.
If you're deliberately using CapturePhotoToStorageFileAsync, check your capabiities.
The Issue is resolved
I Added code for
InitializeAsync()
Created file to be used to store image
using
Windows::Storage::StorageFileRetrievalOperation^ CreateFileOp = Windows::Storage::KnownFolders::PicturesLibrary->CreateFileAsync("Test.jpg");
I found Java script article and implemented in c++.
http://code.msdn.microsoft.com/windowsdesktop/Media-Capture-Sample-adf87622/sourcecode?fileId=43837&pathId=1754477665

edit ListView from C++ clr

I am facing some prob in managed C++, I can fill my ListView , but I am unable to edit specific row at later time
I can fill like
listView1->View = View::Details;
listView1->Columns->Add("S.no",......
ListViewItem^ itmp = gcnew System::Windows::Forms::ListViewItem("100");
ListViewSubItem^ itms1 = gcnew ListViewSubItem(itmp, "12:12:12 PM");
itmp->SubItems->Add(itms1);
listView1->Items->Add(itmp);
I want to implement following VB code in managed C++ , but showing errors
Dim FindlvItem() As ListViewItem // here i am facing problem in conversion to c++ managed
FindlvItem = Me.ListView1.Items.Find("100", False)
FindlvItem(0).SubItems(0).Text = "01:01:01 AM"
I dont want to use foreach loop to save processing
vs.net 2008
You should be able to convert the code almost line for line to C++/CLI. The only problem is that Find will return a collection of list view items, not just a single item.
array<ListViewItem^>^ FindlvItem = ListView1->Items->Find("100",false);
if (FindlvItem->Length == 1)
{
FindlvItem[0]->SubItems[0]->Text = "01:01:01 AM";
} // if found