please, how can i directly pass a bitmap image to a pdf file. I have made a graph with GraphView and at the end i convert it to Bitmap, inside an OnClickListener:
write.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
Bitmap bitmap;
graph.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(graph.getDrawingCache());
graph.setDrawingCacheEnabled(false);
String filename = "imagen";
FileOperations fop = new FileOperations();
fop.write(filename, bitmap);
if (fop.write(filename,bitmap)) {
Toast.makeText(getApplicationContext(),
filename + ".pdf created", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "I/O error",
Toast.LENGTH_SHORT).show();
}
}
});
The problem is that in the class FileOperations:
public FileOperations() {
}
public Boolean write(String fname, Bitmap bm) {
try {
String fpath = "/sdcard/" + fname + ".pdf";
File file = new File(fpath);
if (!file.exists()) {
file.createNewFile();
}
Document document = new Document();
PdfWriter.getInstance(document,
new FileOutputStream(file.getAbsoluteFile()));
document.open();
String filename = bm.toString();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);
document.add(image);
document.add(new Paragraph("Hello World2!"));
// step 5
document.close();
Log.d("Suceess", "Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
I want to know how can i pass the bitmap Image to add it in the pdf document, i do this but i think this works only when i give it a path.
String filename = bm.toString();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);
I just solve it:
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
document.add(myImg);
in the FileOperations class
Related
I am wondering how we can use ITEXT7 to extract image info associated to digital signatures. I know there have been similar questions asked in the past, but they were mostly around ITEXT5, which is quite different from the ITEXT7 after all the updates and modifications to the software.
You can extract the image from a signature appearance using low-level API.
Complete Java code:
private void saveImageFromSignature(PdfDocument document, String fieldName) throws IOException {
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
PdfDictionary xObject = acroForm.getField(name)
.getWidgets()
.get(0)
.getNormalAppearanceObject()
.getAsDictionary(PdfName.Resources)
.getAsDictionary(PdfName.XObject)
.getAsStream(new PdfName("FRM"))
.getAsDictionary(PdfName.Resources)
.getAsDictionary(PdfName.XObject);
PdfStream stream = xObject.getAsStream(new PdfName("Im1"));
PdfImageXObject image = new PdfImageXObject(stream);
BufferedImage result = createImageFromBytes(image.getImageBytes());
//pdf allows using masked image in the signature appearance
PdfStream maskStream = (PdfStream) stream.getAsStream(PdfName.SMask);
if (maskStream != null) {
PdfImageXObject maskImage = new PdfImageXObject(maskStream);
BufferedImage maskBimage = createImageFromBytes(maskImage.getImageBytes());
String fileMask = String.format(getOutputFolder() + "/file_mask_%d.%s",
image.getPdfObject().getIndirectReference().getObjNumber(),
image.identifyImageFileExtension());
ImageIO.write(maskBimage,
image.identifyImageFileExtension(),
new File(fileMask));
//the mask defines an alfa channel
Image transpImg = transformToTransperency(maskBimage);
result = applyTransperency(result, transpImg);
}
String filenameComp = String.format(getOutputFolder() + "/file_comp_%d.%s",
image.getPdfObject().getIndirectReference().getObjNumber(),
image.identifyImageFileExtension());
ImageIO.write(result,
image.identifyImageFileExtension(),
new File(filenameComp));
document.close();
}
private Image transformToTransperency(BufferedImage bi) {
ImageFilter filter = new RGBImageFilter() {
#Override
public int filterRGB(int x, int y, int rgb) {
return (rgb << 8) & 0xFF000000;
}
};
ImageProducer ip = new FilteredImageSource(bi.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
private BufferedImage applyTransperency(BufferedImage bi, Image mask) {
BufferedImage dest = new BufferedImage(
bi.getWidth(), bi.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(bi, 0, 0, null);
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0F);
g2.setComposite(ac);
g2.drawImage(mask, 0, 0, null);
g2.dispose();
return dest;
}
Upd: This works for a very limited number of cases. Thanks for #mkl.
First of all, thank you for the proposals which personally guided me.
After several tries, here is the code that worked for me:
public void extract(String inputFilename, String fieldName) throws IOException {
try (PdfDocument document = new PdfDocument(new PdfReader(inputFilename))){
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
final PdfFormField signatorySignature1 = acroForm.getField(fieldName);
final PdfDictionary appearanceDic = signatorySignature1.getPdfObject().getAsDictionary(PdfName.AP);
final PdfStream normalAppearance = appearanceDic.getAsStream(PdfName.N);
final PdfDictionary ressourceDic = normalAppearance.getAsDictionary(PdfName.Resources);
PdfResources resources = new PdfResources(ressourceDic);
final ImageRenderInfo imageRenderInfo = extractImageRenderInfo(normalAppearance.getBytes(), resources);
Files.write(
Path.of(inputFilename + "_" + fieldName + "_" + System.currentTimeMillis() + ".png"),
imageRenderInfo.getImage().getImageBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
public ImageRenderInfo extractImageRenderInfo(byte[] contentBytes, PdfResources pdfResource) {
MyLocationExtractionStrategy strategy = new MyLocationExtractionStrategy();
PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy, new HashMap<>());
parser.processContent(contentBytes, pdfResource);
return strategy.getImageRenderInfo();
}
class MyLocationExtractionStrategy implements ILocationExtractionStrategy {
private ImageRenderInfo imageRenderInfo;
#Override public Collection<IPdfTextLocation> getResultantLocations() {
return null;
}
#Override public void eventOccurred(IEventData iEventData, EventType eventType) {
if (eventType.equals(EventType.RENDER_IMAGE)) {
imageRenderInfo = (ImageRenderInfo)iEventData;
}
}
#Override public Set<EventType> getSupportedEvents() {
return null;
}
public ImageRenderInfo getImageRenderInfo() {
return this.imageRenderInfo;
}
}
My code is here; I was selecting PDF files from a SD card or internal phone memory using the showFileChooser() method then from onActivityResult(), the files go to mergePdfFiles(View view) method, and from there the files go to createPdf(String[] srcs).
Here is the complete code of my activity:
//Below is onCreate();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mergedpdf);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, locations);
// public void fileSelected(File file ) {
// locations.add(file.toString());
// adapter.notifyDataSetChanged();
// }
NewText = (TextView)findViewById(R.id.textView);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
listView = (ListView)findViewById(R.id.list_items);
btn = (ImageView) findViewById(R.id.imageView8);
btnconvert = (ImageView) findViewById(R.id.imageView11);
btnconvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
try {
createPdf( locations);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(Mergedpdf.this, "button clicked", Toast.LENGTH_SHORT).show();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
showFileChooser();
NewText.setText("Below Files are Selected");
}
});
}
//this is mergedfiles();
public void mergePdfFiles(View view){
Toast.makeText(Mergedpdf.this, "merge function", Toast.LENGTH_SHORT).show();
try {String[] srcs= new String[locations.size()];
for(int i = 0;i<locations.size();i++) {
srcs[i] = locations.get(i);
}
// String[] srcs = {txt1.getText().toString(), txt2.getText().toString()};
createPdf(srcs);
}catch (Exception e){e.printStackTrace();}
}
//This method create merged pdf file
public void createPdf (String[] srcs) {
try {
// Create document object
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Merged-PDFFiles");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
Date date = new Date();
#SuppressLint("SimpleDateFormat") final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
Document document = new Document();
// pdfCopy = new File(docsFolder.getAbsolutePath(),pdf+"Images.pdf");
// Document document = new Document();
//PdfWriter.getInstance(document, output);
// Create pdf copy object to copy current document to the output mergedresult file
PdfCopy copy = new PdfCopy(document, new FileOutputStream(docsFolder + "/" + timeStamp +"combine.pdf"));
Toast.makeText(Mergedpdf.this, "merged pdf saved", Toast.LENGTH_SHORT).show();
// Open the document
document.open();
PdfReader pr;
int n;
for (int i = 0; i < srcs.length; i++) {
// Create pdf reader object to read each input pdf file
pr = new PdfReader(srcs[i].toString());
// Get the number of pages of the pdf file
n = pr.getNumberOfPages();
for (int page = 1; page <= n; page++) {
// Import all pages from the file to PdfCopy
copy.addPage(copy.getImportedPage(pr, page));
}
}
document.close(); // close the document
} catch (Exception e) {
e.printStackTrace();
}
}
//below is showfilechooser(); method
private void showFileChooser () {
Log.e("AA", "bttag=" + btTag);
String folderPath = Environment.getExternalStorageDirectory() + "/";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri, "application/pdf");
Intent intentChooser = Intent.createChooser(intent, "Select a file");
startActivityForResult(intentChooser,PICKFILE_RESULT_CODE);
}
//below is onActivityResult(); method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if (requestCode == PICKFILE_RESULT_CODE) {
if (resultCode == RESULT_OK) {
String FilePath = data.getData().getPath();
locations.add(FilePath);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listview,locations);
listView.setAdapter(adapter);
}
}
}
}
//And my declared variables before oncreate().
public com.itextpdf.text.Document Document;
public PdfCopy Copy;
public ByteArrayOutputStream ms;
TextView NewText;
private TextView txt1;
private Button bt1, bt2,bt3;
private Handler handler;
ListView listView;
ArrayList<String> locations = new ArrayList<>();
ArrayAdapter<String> adapter;
ImageView btn, btnconvert, btn3;
private static final String TAG = "PdfCreator";
private final int PICKFILE_RESULT_CODE=10;
private String btTag = "";
How do I upload a file public and get link ? I am using Dropbox Java core api. Here.
public static void Yukle(File file) throws DbxException, IOException {
FileInputStream fileInputStream = new FileInputStream(file);
InputStream inputStream = fileInputStream;
try (InputStream in = new FileInputStream(file)) {
UploadBuilder metadata = clientV2.files().uploadBuilder("/"+file.getName());
metadata.withMode(WriteMode.OVERWRITE);
metadata.withClientModified(new Date());
metadata.withAutorename(false);
metadata.uploadAndFinish(in);
System.out.println(clientV2.files());
}
}
I use the following code to upload files to DropBox:
public DropboxAPI.Entry uploadFile(final String fullPath, final InputStream is, final long length, final boolean replaceFile) {
final DropboxAPI.Entry[] rev = new DropboxAPI.Entry[1];
rev[0] = null;
Thread t = new Thread(new Runnable() {
public void run() {
try {
if (replaceFile == true) {
try {
mDBApi.delete(fullPath);
} catch (Exception e) {
e.printStackTrace();
}
//! ReplaceFile is always true
rev[0] = mDBApi.putFile(fullPath, is, length, null, true, null);
} else {
rev[0] = mDBApi.putFile(fullPath, is, length, null, null);
}
} catch (DropboxException e) {
e.printStackTrace();
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rev[0];
}
I am stuck on a java project.
I am working with TXT files, and i have the open these TXT files from the JList.
Since i am a total noob at this, it took me a few hours to manage to make the JList work. But now i am stuck at the JTextArea.
The idea is this: clicking on a item from the JList (item = a TXT file from a folder), it should open that TXT file in the JTextArea to view it.
..here is my code so far ..it's a bit long:
-JButton for the search and putting the TXT files in the JList:
JButton searchSearchButton = new JButton("Search");
searchSearchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model1 = new DefaultListModel();
File dir = new File("C:\\Users\\Zoli\\Desktop\\New folder");
File[] matches = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(searchKeywordTextField.getText()) && name.endsWith(".txt");
}
});
for(File f : matches){
model1.addElement(f.getName());
}
searchList.setModel(model1);
}
});
searchSearchButton.setBounds(186, 43, 89, 23);
linuxSearchPane.add(searchSearchButton);
-This is the JTextArea and the JList code:
final JTextArea searchTextArea = new JTextArea();
JScrollPane searchTextAreaScrollPane = new JScrollPane(searchTextArea);
searchTextAreaScrollPane.setBounds(316, 43, 496, 430);
linuxSearchPane.add(searchTextAreaScrollPane);
final JList searchList = new JList();
searchList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
searchList.setVisibleRowCount(20);
searchList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
searchTextArea.setText("");
for(Object o : searchList.getSelectedValuesList()){
searchTextArea.append(o.toString()+"\r\n");
}
}
});
-All i managed to do is, when i select an item from the JList, it prints out the item name in the JTextArea not what it contains in the TXT.
Here is a picture to show you:
picture
could anyone please help me with this...i have zero idea...i have read about JList, and JTextArea, but nothing even points to what i need...
Please help.
I DID IT!!!
Here's the code:
final JTextArea searchTextArea = new JTextArea();
JScrollPane searchTextAreaScrollPane = new JScrollPane(searchTextArea);
searchTextAreaScrollPane.setBounds(316, 43, 496, 430);
linuxSearchPane.add(searchTextAreaScrollPane);
final JList searchList = new JList();
searchList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
searchList.setVisibleRowCount(20);
searchList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
searchTextArea.setText("");
String root = "C:\\Users\\Zoli\\Desktop\\New folder\\";
String filename;
String lineRead = "";
String fileContent = "";
try {
for(Object o : searchList.getSelectedValuesList()){
filename = o.toString();
FileReader reader = new FileReader(root + filename);
BufferedReader buffer = new BufferedReader(reader);
while(lineRead != null){
try {
lineRead = buffer.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}
if(lineRead != null){
fileContent = fileContent + lineRead + "\r\n";
searchTextArea.setText(fileContent);
}
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Also here's the picture to see how it works: picture
I want to save byte[] file into a specific directory :
I get it from this method :
public void setUploadedPicture(UploadedFile uploadedPicture)
{
System.out.println("set : "+uploadedPicture.getFileName()+" size : "+uploadedPicture.getSize());
this.uploadedPicture = uploadedPicture;
}
and I access the byte[] with :
uploadedPicture.getContents()
I tested this link but no result
how to save it into a specific directory either inside my project or outside
thank you
*********EDIT**********
here is the code whic works but sometimes I have the error :
public void setUploadedPicture(UploadedFile uploadedPicture)
{
System.out.println("set : "+uploadedPicture.getFileName()+" size : "+uploadedPicture.getSize());
this.uploadedPicture = uploadedPicture;
InputStream inputStr = null;
try {
inputStr = uploadedPicture.getInputstream();
} catch (IOException e) {
e.printStackTrace();
}
//create destination File
String destPath = "C:\\"+uploadedPicture.getFileName();
File destFile = new File(destPath);
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleFileUpload(FileUploadEvent event) {
//get uploaded file from the event
UploadedFile uploadedFile = (UploadedFile)event.getFile();
//create an InputStream from the uploaded file
InputStream inputStr = null;
try {
inputStr = uploadedFile.getInputstream();
} catch (IOException e) {
//log error
}
//create destination File
String destPath = "your path here";
File destFile = new File(destPath);
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
//log error
}
}