Search Text on Image in vaadin - pdf

I designed a Document Viewer that displays the PDF pages in image format.
I need to implement search functionality on this image formatted pages. When the user enters a term in the search textfield, the term has to be highlighted wherever it is present in the image. This is the code I have tried.
private VerticalLayout buildMainVerticalLayout()
{
mainVerticalLayout = new VerticalLayout();
SwingController controller = new SwingController();
SwingViewBuilder factory = new SwingViewBuilder(controller);
JPanel viewerComponentPanel = factory.buildViewerPanel();
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
JFrame applicationFrame = new JFrame();
applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
applicationFrame.getContentPane().add(viewerComponentPanel);
controller.openDocument("test.pdf");
applicationFrame.pack();
applicationFrame.setVisible(true);
DocumentSearchController searchController =
controller.getDocumentSearchController();
for (String term : terms) {
searchController.addSearchTerm(term, false, false);
}
Document document = controller.getDocument();
ArrayList<WordText> foundWords;
for (int pageIndex = 0; pageIndex < document.getNumberOfPages();
pageIndex++) {
foundWords = searchController.searchPage(pageIndex);
System.out.println("Page " + pageIndex);
if (foundWords != null){
for (WordText wordText : foundWords){
System.out.println(" found hit: " + wordText.toString());
}
}
}
return mainVerticalLayout;
}
But the output showing an error. I have tried with many possibilities. It is just opening the editor, but the PDF isn't loading.
Can anyone help me with this?

Related

How to generate the Thumbnail of the PDF first page in Xamarin Forms

I'm using the Syncfusion PDF viewer for Xamarin Forms to display a collection of PDF files and it seems the conversion from PDF to PNG (to extract the first page (the cover) of the PDF file to show it, to the user, into a carousel) didn't work in Xamarin [see https://www.syncfusion.com/kb/9112/how-to-convert-pdf-to-png]
I wonder if there is a way to convert PDF into PNG on the Xamarin platform or if I should convert it on the server side.
Thank you.
You can export PDF pages to images without using Syncfusion PDF Viewer control by consuming the PdfRenderer , CGPDFDocument, and PdfDocument classes.
Xamarin.Forms.Android:
//initialize PDFRenderer by passing PDF file from location.
PdfRenderer renderer = new PdfRenderer(GetSeekableFileDescriptor());
int pageCount = renderer.PageCount;
for(int i=0;i<pageCount;i++)
{
// Use `openPage` to open a specific page in PDF.
Page page = renderer.OpenPage(i);
//Creates bitmap
Bitmap bmp = Bitmap.CreateBitmap(page.Width, page.Height, Bitmap.Config.Argb8888);
//renderes page as bitmap, to use portion of the page use second and third parameter
page.Render(bmp, null, null, PdfRenderMode.ForDisplay);
//Save the bitmap
SaveImage(bmp);
page.Close();
}
//Method to retrieve PDF file from the location
private ParcelFileDescriptor GetSeekableFileDescriptor()
{
ParcelFileDescriptor fileDescriptor = null;
try
{
string root = Android.OS.Environment.ExternalStorageDirectory.ToString()+ "/Syncfusion/sample.pdf";
fileDescriptor = ParcelFileDescriptor.Open(new Java.IO.File(root),ParcelFileMode.ReadOnly
);
}
catch (FileNotFoundException e)
{
}
return fileDescriptor;
}
Xamarin.Forms.iOS:
public void ConvertToImage(Stream fileStream) //Pass PDF stream
{
MemoryStream stream = new MemoryStream();
// Create memory stream from file stream.
fileStream.CopyTo(stream);
// Create data provider from bytes.
CGDataProvider provider = new CGDataProvider(stream.ToArray());
try
{
//Load a PDF file.
m_pdfDcument = new CGPDFDocument(provider);
}
catch (Exception)
{
}
//Get PDF's page and convert as image.
using (CGPDFPage pdfPage = m_pdfDcument.GetPage(2))
{
//initialise image context.
UIGraphics.BeginImageContext(pdfPage.GetBoxRect(CGPDFBox.Media).Size);
// get current context.
CGContext context = UIGraphics.GetCurrentContext();
context.SetFillColor(1.0f, 1.0f, 1.0f, 1.0f);
// Gets page's bounds.
CGRect bounds = new CGRect(pdfPage.GetBoxRect(CGPDFBox.Media).X, pdfPage.GetBoxRect(CGPDFBox.Media).Y, pdfPage.GetBoxRect(CGPDFBox.Media).Width, pdfPage.GetBoxRect(CGPDFBox.Media).Height);
if (pdfPage != null)
{
context.FillRect(bounds);
context.TranslateCTM(0, bounds.Height);
context.ScaleCTM(1.0f, -1.0f);
context.ConcatCTM(pdfPage.GetDrawingTransform(CGPDFBox.Crop, bounds, 0, true));
context.SetRenderingIntent(CGColorRenderingIntent.Default);
context.InterpolationQuality = CGInterpolationQuality.Default;
// Draw PDF page in the context.
context.DrawPDFPage(pdfPage);
// Get image from current context.
pdfImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
}
}
// Get bytes from UIImage object.
using (var imageData = pdfImage.AsPNG())
{
imageBytes = new byte[imageData.Length];
System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, imageBytes, 0, Convert.ToInt32(imageData.Length));
//return bytes;
}
//Create image from bytes.
imageStream = new MemoryStream(imageBytes);
//Save the image. It is a custom method to save the image
Save("PDFtoImage.png", "image/png", imageStream);
}
Xamarin.Forms.UWP
public async void ConvertToImage(Stream fileStream) //Pass PDF stream
{
StorageFile file = null;
//Creates file picker to choose PDF file.
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".pdf");
filePicker.ViewMode = PickerViewMode.Thumbnail;
filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
filePicker.SettingsIdentifier = "picker1";
filePicker.CommitButtonText = "Open Pdf File";
//Open file picker option
file = await filePicker.PickSingleFileAsync();
// Load selected PDF file from the file picker.
PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(file);
if (pdfDocument != null && pdfDocument.PageCount > 0)
{
for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++)
{
//Get page from a PDF file.
var pdfPage = pdfDocument.GetPage((uint)pageIndex);
if (pdfPage != null)
{
//Create temporary folder to store images.
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
//Create image file.
StorageFile destinationFile = await KnownFolders.CameraRoll.CreateFileAsync(Guid.NewGuid().ToString() + ".jpg");
if (destinationFile != null)
{
IRandomAccessStream randomStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite);
//Crerate PDF rendering options
PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions();
pdfPageRenderOptions.DestinationWidth = (uint)(300);
// Render the PDF's page as stream.
await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions);
await randomStream.FlushAsync();
//Dispose the random stream
randomStream.Dispose();
//Dispose the PDF's page.
pdfPage.Dispose();
}
}
}
}
}
I work for Syncfusion.

How do I make modifications to existing layer(Optional Content Group) in pdf?

I am implementing functionality to allow user to draw figures in pdf. I want to draw all the figures in a single layer, which can be made visible or invisible by the user.I am able to create a new layer in a pdf. I am also able to retrieve that layer.But, I am not able to make modification to layer (PDOptionalContentGroup). I tried converting the PDOptionalContentGroup to PDPage and then making desired changes to PDPPage. I also saved the PDDocument.It only created another layer with the same name as previous one, but the changes were not there.Here is the code that I used:
PDFont font = PDType1Font.HELVETICA;
PDDocument doc = PDDocument.load(src);
PDOptionalContentProperties ocprops = doc.getDocumentCatalog().getOCProperties();
foreach (string groupName in ocprops.getGroupNames())
{
PDOptionalContentGroup group = ocprops.getGroup(groupName);
COSBase cosbase = group.getCOSObject();
PDPage groupPage = new PDPage((COSDictionary)cosbase);
PDPageContentStream cs = new PDPageContentStream(doc, groupPage, true, false);
cs.beginText();
cs.setFont(font, 12);
cs.moveTextPositionByAmount(150, 200);
cs.drawString("Testing added to group:" + groupName);
cs.endText();
cs.close();
doc.save(src);
}
(In a comment the OP indicated that he can only use a 1.8.x version of PDFBox. Thus, the code here is 1.8'ish, tested against PDFBox 1.8.12 for Java.)
In a comment to your question "How to get resource names for optional content group in a pdf?" Tilman Hausherr suggested to use the PDFBox class LayerUtility as template for own solutions.
Thus, as an example how add to an existing OCG this helper method (based on LayerUtility.appendFormAsLayer) shows how to add text to an existing or new OCG. It should be simple to adapt it to adding the content you want to add...
void addTextToLayer(PDDocument document, int pageNumber, String layerName, float x, float y, String text) throws IOException
{
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDOptionalContentProperties ocprops = catalog.getOCProperties();
if (ocprops == null)
{
ocprops = new PDOptionalContentProperties();
catalog.setOCProperties(ocprops);
}
PDOptionalContentGroup layer = null;
if (ocprops.hasGroup(layerName))
{
layer = ocprops.getGroup(layerName);
}
else
{
layer = new PDOptionalContentGroup(layerName);
ocprops.addGroup(layer);
}
PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(pageNumber);
PDResources resources = page.findResources();
if (resources == null)
{
resources = new PDResources();
page.setResources(resources);
}
PDPropertyList props = resources.getProperties();
if (props == null)
{
props = new PDPropertyList();
resources.setProperties(props);
}
//Find first free resource name with the pattern "MC<index>"
int index = 0;
PDOptionalContentGroup ocg;
COSName resourceName;
do
{
resourceName = COSName.getPDFName("MC" + index);
ocg = props.getOptionalContentGroup(resourceName);
index++;
} while (ocg != null);
//Put mapping for our new layer/OCG
props.putMapping(resourceName, layer);
PDFont font = PDType1Font.HELVETICA;
PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true, true);
contentStream.beginMarkedContentSequence(COSName.OC, resourceName);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(x, y);
contentStream.drawString(text);
contentStream.endText();
contentStream.endMarkedContentSequence();
contentStream.close();
}
(AddContentToOCG helper method addTextToLayer)
You can use it like this
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
addTextToLayer(document, 0, "MyLayer", 30, 600, "Text in new layer 'MyLayer'");
addTextToLayer(document, 0, "MyOtherLayer", 230, 550, "Text in new layer 'MyOtherLayer'");
addTextToLayer(document, 0, "MyLayer", 30, 500, "Text in existing layer 'MyLayer'");
addTextToLayer(document, 0, "MyOtherLayer", 230, 450, "Text in existing layer 'MyOtherLayer'");
document.save(new File(RESULT_FOLDER, "TextInOCGs.pdf"));
document.close();
(AddContentToOCG test method testAddContentToNewOrExistingOCG)
to add text to existing or not yet existing OCGs.

How to display an image in PdfBox 2.0.3?

Can someone give me an example on how to display image in PDF file using Apache PDFBox 2.0.3?
Thanks in advance
You might want to look at the pdfbox examples directory in the Apache SVN repository, in particular the aptly named example class AddImageToPDF with this pivotal method:
public void createPDFFromImage( String inputFile, String imagePath, String outputFile )
throws IOException
{
// the document
PDDocument doc = null;
try
{
doc = PDDocument.load( new File(inputFile) );
//we will add the image to the first page.
PDPage page = doc.getPage(0);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
// contentStream.drawImage(ximage, 20, 20 );
// better method inspired by http://stackoverflow.com/a/22318681/535646
// reduce this value if the image is too large
float scale = 1f;
contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth()*scale, pdImage.getHeight()*scale);
contentStream.close();
doc.save( outputFile );
}
finally
{
if( doc != null )
{
doc.close();
}
}
}

Pdf file is not viewing in android app

Anyone can help in this code, the pdf file is not loading in app and just showing blank white screen, Logcat showing FileNotFoundExeeption: /storage/sdcard/raw/ourpdf.pdf.
i am trying to make an app that will show information while i click buttons and every button will be active for specific pdf file reading. Any specific help please.
Thanks for help
part1
package com.code.androidpdf;
public class MainActivity extends Activity {
//Globals:
private WebView wv;
private int ViewSize = 0;
//OnCreate Method:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Settings
PDFImage.sShowImages = true; // show images
PDFPaint.s_doAntiAlias = true; // make text smooth
HardReference.sKeepCaches = true; // save images in cache
//Setup above
wv = (WebView)findViewById(R.id.webView1);
wv.getSettings().setBuiltInZoomControls(true);//show zoom buttons
wv.getSettings().setSupportZoom(true);//allow zoom
//get the width of the webview
wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
ViewSize = wv.getWidth();
wv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
pdfLoadImages();//load images
}
private void pdfLoadImages() {
try
{
// run async
new AsyncTask<Void, Void, Void>()
{
// create and show a progress dialog
ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "", "Opening...");
#Override
protected void onPostExecute(Void result)
{
//after async close progress dialog
progressDialog.dismiss();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
// select a document and get bytes
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/randompdf.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
net.sf.andpdf.nio.ByteBuffer bb = null ;
raf.close();
// create a pdf doc
PDFFile pdf = new PDFFile(bb);
//Get the first page from the pdf doc
PDFPage PDFpage = pdf.getPage(1, true);
//create a scaling value according to the WebView Width
final float scale = ViewSize / PDFpage.getWidth() * 0.95f;
//convert the page into a bitmap with a scaling value
Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
//save the bitmap to a byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
byte[] byteArray = stream.toByteArray();
//convert the byte array to a base64 string
String base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
//create the html + add the first image to the html
String html = "<!DOCTYPE html><html><body bgcolor=\"#7f7f7f\"><img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
//loop through the rest of the pages and repeat the above
for(int i = 2; i <= pdf.getNumPages(); i++)
{
PDFpage = pdf.getPage(i, true);
page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
stream = new ByteArrayOutputStream();
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
byteArray = stream.toByteArray();
base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
html += "<img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
}
html += "</body></html>";
//load the html in the webview
wv.loadDataWithBaseURL("", html, "text/html","UTF-8", "");
}
catch (Exception e)
{
Log.d("CounterA", e.toString());
}
return null;
}
}.execute();
System.gc();// run GC
}
catch (Exception e)
{
Log.d("error", e.toString());
}
}
}
It is (sadly) not possible to view a PDF that is stored locally in your devices. Android L has introduced the feature. So, to display a PDF , you have two options:
See this answer for using webview
How to open local pdf file in webview in android? (note that this requires an internet connection)
Use a third party pdf Viewer.
You can also send an intent for other apps to handle your pdf.
You can get an InputStream for the file using
getResources().openRawResource(R.raw.ourpdf)
Docs: http://developer.android.com/reference/android/content/res/Resources.html#openRawResource(int)

iTextSharp document close is causing an extra blank page

I am using the PdfPageEventHelper in order to be able to add Header and Footer to each page of my document automatically. As was mentioned in many places I am doing so while overriding the OnEndPage.
On my class I am creating:
PdfDocument
creating a FileStream
getting a PdfWriter vis the the static GetInstance method
setting the specific PdfPageEventHelper class that I've created to the writer.PageEvent
adding the writer to the document
calling the document open
adding some content to the document (one very small table having one row)
calling the close document
Now - at step #8 the OnEndPage is being called, which is great, but somehow it is being called twice!
both times it is called to page number 1 (as I see on runtime in the document parameter)
therefore I am getting 2 pages in my document instead of one, where the second page is empty, and the first page is actually having my header and footer twice (overlapping).
I am using iTextSharp version 5.5.1.0 , and I saw on the source file that in Document.Close method they are calling NewPage function... this is why I am getting to OnEndPage in the 2nd time.
Any suggestions?
class MyPdfWriter
{
public MyPdfWriter()
{
//generate doc, file stream etc.
_document = _document = new PdfDocument();
_document.SetMargins(15, 15, 50, 50);
_document.SetPageSize(PageSize.A4);
_fs = new FileStream("myTest.pdf", FileMode.Create);
_writer = PdfWriter.GetInstance(_document, _fs);
_writer.PageEmpty = false;
_writer.PageEvent = new PdfPage(reportDetails.Header,reportDetails.Footer,reportDetails.LogoImage, reportDetails.ReportFileName);
//open doc
_document.Open();
//add some content
var table = new PdfPTable(1);
table.AddCell("bla bla");
_document.Add(titleTable);
//close doc, stream etc.
if (_document != null && _document.IsOpen())
{
_document.Close();
_document = null;
}
if (_writer != null)
{
_writer.Close();
_writer = null;
}
if (_fs != null)
{
_fs.Close();
_fs.Dispose();
}
}
}
class PdfPage : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
var footer = new PdfPTable(2);
//Write some cells to footer
//....
//init the width
footer.TotalWidth = (footer.TotalWidth.CompareTo(0f) != 0) ? footer.TotalWidth : document.PageSize.Width;
//write the table with WriteSelectedRows
footer.WriteSelectedRows(0, -1, document.LeftMargin, footer.TotalHeight + 10f, writer.DirectContent);
var Header = new PdfPTable(2);
//Write some cells to Header
//....
//init the width
Header.TotalWidth = (Header.TotalWidth.CompareTo(0f) != 0) ? Header.TotalWidth : document.PageSize.Width;
//write the table with WriteSelectedRows
Header.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 10,
writer.DirectContent);
}
}