Anyone Know the code for converting Word to PDF / PDF to Word in ANDROID...
If you Know
Please Share me....
Already tried:
Jars:
docx4j-3.0.0.jar
Code:
try
{
long start = System.currentTimeMillis();
InputStream is = new FileInputStream(
new File("file1"));
Toast.makeText(getApplicationContext(), "is", Toast.LENGTH_SHORT).show();
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(is);
List sections = wordMLPackage.getDocumentModel().getSections();
for (int i = 0; i < sections.size(); i++) {
System.out.println("sections Size" + sections.size());
/* wordMLPackage.getDocumentModel().getSections().get(i)
.getPageDimensions().setHeaderExtent(3000);*/
}
Mapper fontMapper = new IdentityPlusMapper();
PhysicalFont font = (PhysicalFont) PhysicalFonts.getPhysicalFonts().get(
"Comic Sans MS");
fontMapper.getFontMappings().put("Algerian", font);
wordMLPackage.setFontMapper(fontMapper);
PdfSettings pdfSettings = new PdfSettings();
org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
wordMLPackage);
OutputStream out = new FileOutputStream(new File(
"file1/sampleeee.pdf"));
conversion.output(out, pdfSettings);
System.err.println("Time taken to Generate pdf "
+ (System.currentTimeMillis() - start) + "ms");
}
catch(Exception e)
{
e.printStackTrace();
}
But I cant get the output...
One reason why you "cant get the output" is because you are providing an incorrect FileOutputStream. You need to be using either:
Internal storage (openOutputStream(), getFilesDir(), etc.), or
External storage (getExternalFilesDir(), etc.)
Related
I'm using iText to generate a PDF.Pdf is generated for showing some records in a school, so I need to show a school Emblem and school name at the center of the top header of the first page. I have the string HTTP URL of the image file which may be of any size. I want to resize the image without losing its quality and adjust it at the header portion(so it make sense) and need to show the school name below. My problem is I don't know how to add the image so it is displayed in the "header box".
Here there are some code snippets ...
private void createPdf() {
try {
String imgURL = "http URL";
String schoolName = "School Name";
File filePath = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOCUMENTS), "PROJECT");
if (! filePath.exists()){
if (! filePath.mkdirs()){
}else{
}
}
// Create a file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
fileExp = new File(filePath+"/Report_"+ timeStamp + ".pdf");
photoURI = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".fileprovider", fileExp);
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(fileExp));
document.open();
addMetaData(document);
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
Paragraph para1 = new Paragraph(repHeader, catFont);
para1.setAlignment(Element.ALIGN_CENTER);
preface.add(para1);
addEmptyLine(preface, 2);
Paragraph para3 = new Paragraph("Period : ", textBold);
Chunk perChunk3 = new Chunk("from "+edtFromDate.getText().toString()+" to "+edtToDate.getText().toString(),textNormal);
para3.add(perChunk3);
preface.add(para3);
addEmptyLine(preface, 1);
document.close();
//insertDocument("Report_"+ timeStamp + ".pdf");
Intent emailIn = new Intent(Intent.ACTION_SEND);
emailIn.setType("application/pdf");
emailIn.putExtra(Intent.EXTRA_STREAM, photoURI);
emailIn.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIn.putExtra(Intent.EXTRA_EMAIL, new String[] { selEmailId });
emailIn.putExtra(Intent.EXTRA_SUBJECT, "Report : "+repHeader);
emailIn.putExtra(Intent.EXTRA_TEXT, repHeader);
startActivityForResult(Intent.createChooser(emailIn, "E-mail"),15);
} catch (Exception e) {
e.printStackTrace();
}
}
Below is the dependency :
implementation 'com.itextpdf:itextg:5.5.10'
You can add an image to the document and scale as the image by preferred height or width using the below code
Here I have scaled the image width according to the preferredImageHeight
Image image = Image.getInstance("https://static.wikia.nocookie.net/rickandmorty/images/9/95/HarryherpsonHS.jpg/revision/latest/top-crop/width/360/height/360?cb=20150908094923");
image.setAlignment(Element.ALIGN_CENTER);
System.out.println("Image width: " + image.getScaledWidth() + ", height: " + image.getScaledHeight());
float preferredImageHeight = 60;
float widthScale = image.getScaledHeight() / preferredImageHeight;
image.scaleAbsolute(image.getScaledWidth() / widthScale, preferredImageHeight);
System.out.println("Image width: " + image.getScaledWidth() + ", height: " + image.getScaledHeight());
document.add(image);
I would follow the instructions here https://memorynotfound.com/adding-header-footer-pdf-using-itext-java/ and customise their code to suit.
for the purposes of keeping answers here, the basic is that you need to create an "addHeader" method just before your document.close()
using something similar to this code block
private void addHeader(PdfWriter writer){
PdfPTable header = new PdfPTable(2);
try {
// set defaults
header.setWidths(new int[]{2, 24});
header.setTotalWidth(527);
header.setLockedWidth(true);
header.getDefaultCell().setFixedHeight(40);
header.getDefaultCell().setBorder(Rectangle.BOTTOM);
header.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
// add image
Image logo = Image.getInstance(HeaderFooterPageEvent.class.getResource("/memorynotfound-logo.jpg"));
header.addCell(logo);
// add text
PdfPCell text = new PdfPCell();
text.setPaddingBottom(15);
text.setPaddingLeft(10);
text.setBorder(Rectangle.BOTTOM);
text.setBorderColor(BaseColor.LIGHT_GRAY);
text.addElement(new Phrase("iText PDF Header Footer Example", new Font(Font.FontFamily.HELVETICA, 12)));
text.addElement(new Phrase("https://memorynotfound.com", new Font(Font.FontFamily.HELVETICA, 8)));
header.addCell(text);
// write content
header.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
} catch(DocumentException de) {
throw new ExceptionConverter(de);
} catch (MalformedURLException e) {
throw new ExceptionConverter(e);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
I'm targeting now android 11 and all of us know about scoped storage,
my case is that I need to access all pdfs files on the phone it's working for any android less than android 11.
I've tried to grant permission android.permission.MANAGE_EXTERNAL_STORAGE but, I don't know why it fails with me, I'm able to read jpg patter files but, the pdf files I can't.
this is my code:
public ArrayList<PdfData> Search_Dir(File dir) {
String pdfPattern = ".pdf";
File[] FileList = dir.listFiles();
if (FileList != null) {
for (int i = 0; i < FileList.length; i++) {
File file = FileList[i];
if (file.isDirectory()) {
Search_Dir(file);
} else {
if (file.getName().endsWith(pdfPattern)) {
Log.v("fileNameIs ", " " + i + file.getName());
String file_size = Formatter.formatShortFileSize(getApplicationContext(), file.length());
PdfData pdfData = new PdfData();
pdfData.setFile(file);
pdfData.setFileName(file.getName());
pdfData.setFileSize(file_size);
pdfDataList.add(pdfData);
Log.v("fileSize is : ", ": " + file_size);
}
}
}
}
return pdfDataList;
}
i call the method like that
list = Search_Dir(Environment.getExternalStorageDirectory());
I have a listview that is being filled from my database. Now I want to take the contents of this listview and show it in html table.
How I can take my listview and write its contents to html file?
I just did something very similar here.
private File saveResults() {
/*
* Write the results to a file.
*/
List<RiderResult> Results = DataModel.get().getResults();
try {
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Toast.makeText(SummaryFragment.this.getContext(), "Unable to access external storage.",
Toast.LENGTH_SHORT).show();
return null;
}
/*
* Create a file folder in external storage.
*/
File csvDir = new File(
Environment.getExternalStorageDirectory(),
"Android/data/ca.mydomain.myapp/results");
if (!csvDir.exists())
csvDir.mkdirs();
/*
* Create a file in the folder, with today's date and time as the name.
*/
Date dateNow = new Date ();
SimpleDateFormat dateformatYYYYMMDD = new SimpleDateFormat("yyyyMMddHHmm");
StringBuilder nowMMDDYYYY = new StringBuilder( dateformatYYYYMMDD.format( dateNow ) );
File csvFile = new File(csvDir, "result_" + nowMMDDYYYY + ".csv");
BufferedWriter bw = new BufferedWriter(new FileWriter(csvFile, false));
/*
* Write a header row.
*/
bw.write("Finish Seq, Start Num,Clock Time, Actual Time\n");
/*
* and a row for each result, comma separated
*/
for (int i = 0; i < Results.size(); i++) {
String row = new String();
row = "" + (i + 1) + "," + Results.get(i).getStartNo()
+ "," + Results.get(i).getClockTimeString() + ","
+ Results.get(i).getActualTimeString() +"\n";
bw.write(row);
}
bw.close();
/*
* Return the File to the user - for use in a message or email attachment.
*/
return csvFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I was writing to a file which I later attach to an email or send via BlueTooth, or just leave it on file. My file is CSV (race results) and the name of the file is generated. But you can adapt for your use.
I am creating a video from images via FFMPEG and I am able to get the video from images. I am also making use of JavaCV to merge two videos and I am able to join videos using JavaCV without any issues provided both the videos are taken via camera, i.e, a video actually recorded via mobile camera.
Issue that I'm facing :
I am not able to merge the video that was generated from FFMPEG using the images along with the video user has chosen which will mostly be a video that was not generated and taken via mobile camera.
CODE :
Code to generate Video via Images :
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(path + "/" + "dec16.mp4", 800, 400);
try {
recorder.setVideoCodec(avcodec.AV_CODEC_ID_MPEG4);
//recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
recorder.setVideoCodecName("H264");
recorder.setVideoOption("preset", "ultrafast");
recorder.setFormat("mp4");
recorder.setFrameRate(frameRate);
recorder.setVideoBitrate(60);
recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);
startTime = System.currentTimeMillis();
recorder.start();
for(int j=0;j<MomentsGetStarted.chosen_images_uri.size();j++)
{
if(MomentsGetStarted.chosen_images_uri.get(j).video_id==0)
{
chosen_images.add(MomentsGetStarted.chosen_images_uri.get(j));
}
}
for (int i = 0; i < chosen_images.size(); i++) {
opencv_core.IplImage image = cvLoadImage(chosen_images.get(i).sdcardPath);
long t = 3000 * (System.currentTimeMillis() - startTime);
if (t > recorder.getTimestamp()) {
recorder.setTimestamp(t);
recorder.record(image);
}
}
recorder.stop();
} catch (Exception e) {
e.printStackTrace();
}
Code to merge Videos :
int count = file_path.size();
System.out.println("final_joined_list size " + file_path.size());
if (file_path.size() != 1) {
try {
Movie[] inMovies = new Movie[count];
mediaStorageDir = new File(
Environment.getExternalStorageDirectory()
+ "/Pictures");
for (int i = 0; i < count; i++) {
File file = new File(file_path.get(i));
System.out.println("fileeeeeeeeeeeeeeee " + file);
System.out.println("file exists!!!!!!!!!!");
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
inMovies[i] = MovieCreator.build(fc);
fis.close();
fc.close();
}
List<Track> videoTracks = new LinkedList<Track>();
List<Track> audioTracks = new LinkedList<Track>();
Log.d("Movies length", "isss " + inMovies.length);
if (inMovies.length != 0) {
for (Movie m : inMovies) {
for (Track t : m.getTracks()) {
if (t.getHandler().equals("soun")) {
audioTracks.add(t);
}
if (t.getHandler().equals("vide")) {
videoTracks.add(t);
}
if (t.getHandler().equals("")) {
}
}
}
}
Movie result = new Movie();
System.out.println("audio and videoo tracks : "
+ audioTracks.size() + " , " + videoTracks.size());
if (audioTracks.size() > 0) {
result.addTrack(new AppendTrack(audioTracks
.toArray(new Track[audioTracks.size()])));
}
if (videoTracks.size() > 0) {
result.addTrack(new AppendTrack(videoTracks
.toArray(new Track[videoTracks.size()])));
}
IsoFile out = null;
try {
out = (IsoFile) new DefaultMp4Builder().build(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long timestamp = new Date().getTime();
String timestampS = "" + timestamp;
File storagePath = new File(mediaStorageDir
+ File.separator);
storagePath.mkdirs();
File myMovie = new File(storagePath, String.format("%s.mp4", timestampS));
FileOutputStream fos = new FileOutputStream(myMovie);
FileChannel fco = fos.getChannel();
fco.position(0);
out.getBox(fco);
fco.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String mFileName = Environment.getExternalStorageDirectory()
.getAbsolutePath();
// mFileName += "/output.mp4";
File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(mediaStorageDir + File.separator);
for (File f : yourDir.listFiles()) {
if (f.isFile())
name = f.getName();
// make something with the name
}
mFileName = mediaStorageDir.getPath() + File.separator
+ "output-%s.mp4";
System.out.println("final filename : "
+ mediaStorageDir.getPath() + File.separator
+ "output-%s.mp4" + "names of files : " + name);
single_video = false;
return name;
} else {
single_video = true;
name = file_path.get(0);
return name;
}
Error :
The Error that I am facing while trying to merge the videos generated via Images and a normal video is
12-15 12:26:06.155 26022-26111/? W/System.err﹕ java.io.IOException: Cannot append com.googlecode.mp4parser.authoring.Mp4TrackImpl#45417c38 to com.googlecode.mp4parser.authoring.Mp4TrackImpl#44ffac60 since their Sample Description Boxes differ
12-15 12:26:06.155 26022-26111/? W/System.err﹕ at com.googlecode.mp4parser.authoring.tracks.AppendTrack.<init>(AppendTrack.java:48)
Fix that I tried :
Google advised me to change the CODEC in JavaCV from avcodec.AV_CODEC_ID_MPEG4 to avcodec.AV_CODEC_ID_H264. But when I did that, I am not able to get the video from images thereby throwing the following error :
12-15 12:26:05.840 26022-26089/? W/linker﹕ libavcodec.so has text relocations. This is wasting memory and is a security risk. Please fix.
12-15 12:26:05.975 26022-26089/? W/System.err﹕ com.googlecode.javacv.FrameRecorder$Exception: avcodec_open2() error -1: Could not open video codec.
12-15 12:26:05.975 26022-26089/? W/System.err﹕ at com.googlecode.javacv.FFmpegFrameRecorder.startUnsafe(FFmpegFrameRecorder.java:492)
12-15 12:26:05.975 26022-26089/? W/System.err﹕ at com.googlecode.javacv.FFmpegFrameRecorder.start(FFmpegFrameRecorder.java:267)
What I need :
Creating video from Images is inevitable and that video will definitely be used to merge with other videos which might have any Codec Formats. So I need to find a way to merge any kind of videos irrespective of their Codecs or any other parameters. I am trying to keep it simple by just using the Jars and SO files and I dont want to drive myself crazy by going on a full scale implementation of FFMPEG Library. That being said, I am also ready to look into that library if I dont have any other ways to achieve what I want but a solid resource with an ALMOST working code would be much appreciated. Cheers.
Update :
I looked upon the issues mentioned at GitHub of OpenCV, but didnt find anything solid from it.
OpenCV Issues
You are using an MP4 parser which means it won't touch the encoding of the videos. This will only work if the two videos share the same encoder settings like resolution, framerate to list some of the most obvious ones.
If you need to merge videos with different codecs or parameters then you must re-encode them to target a common format and set of parameters and in this case a simple MP4 parser won't do.
You can achieve this directly with ffmpeg.
I'm working on an Android application that should allow the users to share their content via Gmail. I'm using android version 2.2(Froyo).
The problem is that I can't find any working solution for this, I tried almost everything ,but with no luck.
this is the code I'm using:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);;
sharingIntent.setType("application/zip");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
getString(R.string.share_subject));
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.share_body));
String zipFile = FileProvider.URI_AUTHORITY + File.separator + mItemSelected.getLibraryName() + File.separator + mItemSelected.getZipFileName();
sharingIntent.putExtra(Intent.EXTRA_STREAM, android.net.Uri.parse(zipFile));
startActivity(Intent.createChooser(sharingIntent, (getString(R.string.share_chooser))));
}
The problem in this case is that the Gmail app, for no obvious reason, is replacing the mime type of the file, and show the file as text/html, and then my application is not shown in the application list that can deal with this kind of file. Another restriction is that I don't want to use text/html in my intent filter, because I want it to be focused as much as possible, and if it were possible I would define my own mime type...
I did a little research and found this question, but with no answers...
More mime types I tried:
application/x-compressed, application/x-zip-compressed
multipart/x-zip and application/octet-stream
Is there any solution for this problem ??
Thanks.
after a lot of trouble, I discovered that Gmail, launched via Intent, does not like attachments whose prefix is .zip.
So, I succeeded in sending the attachments after renaming it ".vip".
Here is a piece of code (outFile is a zipped file renamed as ".vip"):
enter
private void sendMail(File outFile) {
Uri uriToZip = Uri.fromFile(outFile);
String sendText = "Dear friend,\n\n...";
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[] { "checcodotti#gmail.com" });
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, sendText);
sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Log of the test " + expFilename);
// sendIntent.setType("image/jpeg");
// sendIntent.setType("message/rfc822");
sendIntent.setType("*/*");
sendIntent.putExtra(android.content.Intent.EXTRA_STREAM, uriToZip);
startActivity(Intent.createChooser(sendIntent, "Send Attachment !:"));
}
Please let me know if it helps.
Regards
FD
I improve my previous answer for the part concerning "zipping". Now the are no problems with .zip attachments sent via GMail or whatever. Try this:
{
int lung;
FileInputStream in;
FileOutputStream out;
byte[] buffer = new byte[DIM_BUFFER];
// compress the file to send
String inPath = ctx.getApplicationContext().getFilesDir().getAbsolutePath();
outFile = new File(outPath,TestEdit.ZIPNAME);
// outFile = new File(outPath,filename + ".vip");
in = new FileInputStream(inFile);
ZipEntry entry = new ZipEntry(filename + ".csv");
try{
out = new FileOutputStream(outFile);
// GZIPOutputStream zos;
ZipOutputStream zos;
zos = new ZipOutputStream(new BufferedOutputStream(out) );
zos.putNextEntry(entry);
try {
while ((lung=in.read(buffer)) > 0) {
Log.v(TAG, "Lunghezza di in=" + lung + ". Lungh di buffer=" + buffer.length );
if (buffer.length == lung) {
zos.write(buffer);
} else {
// Gestione del caso in cui il buffer non sia pieno
for (int b = 0; b < lung; b++) {
zos.write(buffer[b]);
}
}
}
} finally {
zos.closeEntry();
zos.close();
in.close();
out.close();
}
}
}