I need to make notification on screen after pdf file had dowloaded. File dowload? but I cannot do notification on screen.
public void createDocumentAboutRegistration(User user){
PdfDocument myPdfDocument = new PdfDocument();
PdfDocument.PageInfo myPageInfo = new PdfDocument.PageInfo.Builder(300,600,1).create();
PdfDocument.Page myPage = myPdfDocument.startPage(myPageInfo);
Paint myPaint = new Paint();
String myString = user.toString();
int x = 10, y=25;
for (String line:myString.split("\n")){
myPage.getCanvas().drawText(line, x, y, myPaint);
y+=myPaint.descent()-myPaint.ascent();
}
myPdfDocument.finishPage(myPage);
String myFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
String nameFile = "coupon-" + user.lastName + ".pdf";
File myFile = new File(myFilePath, nameFile);
try {
myPdfDocument.writeTo(new FileOutputStream(myFile));
Toast.makeText(RegistrationActivity.this, "Coupon generated and saved in your downloads.", Toast.LENGTH_LONG).show();
}
catch (Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this, "Error", Toast.LENGTH_LONG).show();
}
myPdfDocument.close();
}
Related
I am trying to get multiple images from the gallery and make them a PDF here is the code. In the code, I can take multiple images from the user and also make them PDF. But the PDF contains only one image even though I selected multiple images it only shows one image in pdf. I have attached the code below.
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
bitmaps = new ArrayList < > ();
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
try {
Uri uri = clipData.getItemAt(i).getUri();
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmaps.add(bitmap);
pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), bitmaps.size())
.create();
for (int k = 0; k <= i; k++) {
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#FFFFFF"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
canvas.drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
}
bitmap.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
}
File root = new File(Environment.getExternalStorageDirectory(), "PDF Folder");
if (!root.exists()) {
root.mkdir();
}
File file = new File(root, "image" + ".pdf");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
pdfDocument.writeTo(fileOutputStream);
pdfDocument.close();
} catch (IOException io) {
io.printStackTrace();
} catch (NullPointerException n) {
n.printStackTrace();
}
}
}
I am unable to print pdf with MONOCHROME option on MAC, even
monochrome option is selected but still on MAC its printing in
COLOR but on windows its working fine for both options MONOCHROME and COLOR.
Plus, On MAC settings are disable even proper printer is connected.
but the same code running on windows its working fine in every
scenario.
I am using macOS High Sierra version 10.13.6
public boolean printFile(String fileUrl) {
PrintService[] printServicesAll = PrintServiceLookup.lookupPrintServices(null, null);
PrintService[] printServicesFiltered;
PrintRequestAttributeSet attrib = new HashPrintRequestAttributeSet();
Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
String OS = System.getProperty("os.name").toLowerCase();
attrib.add(new Copies(1));
attrib.add(new sun.print.DialogOnTop());
attrib.add(Chromaticity.MONOCHROME);
attrib.add(DialogTypeSelection.NATIVE);
PrintService selectedPrintService = null;
if (OS.contains("win")) {
if (printServicesAll.length > 0) {
printServicesFiltered = removeLogicalPrinters(printServicesAll);
selectedPrintService = ServiceUI.printDialog(null, screen.width / 3, screen.height / 3, printServicesFiltered, printServicesFiltered[0], null, attrib);
}
} else if (OS.contains("mac")) {
if (printServicesAll.length > 0) {
selectedPrintService = ServiceUI.printDialog(null, screen.width / 3, screen.height / 3, printServicesAll, printServicesAll[0], null, attrib);
}
}
if (attrib.get(Destination.class) != null) {
JOptionPane.showMessageDialog(null, "Print to file option not allowed!");
return false;
} else {
if (selectedPrintService != null)
System.out.println("selected printer: " + selectedPrintService.getName());
else
return false;
try {
DocPrintJob job = selectedPrintService.createPrintJob();
job.addPrintJobListener(new PrintJobAdapter() {
public void printDataTransferCompleted(PrintJobEvent event) {
System.out.println("data transfer complete");
}
public void printJobNoMoreEvents(PrintJobEvent event) {
System.out.println("received no more events");
}
});
print(selectedPrintService, fileUrl, attrib);
/*File file = new File(filePath);
Desktop.getDesktop().print(file);*/
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Main Print File Method
private boolean print(PrintService printService, String fileUrl, PrintRequestAttributeSet attributes)
throws PrintException {
try {
PDDocument pdf = null;
String fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
if (fileType.equalsIgnoreCase("bmp") || fileType.equalsIgnoreCase("gif") || fileType.equalsIgnoreCase("jpg") || fileType.equalsIgnoreCase("png")) {
try {
InputStream in = new URL(fileUrl).openStream();
PDDocument document = new PDDocument();
BufferedImage bImg = ImageIO.read(in);
float width = bImg.getWidth();
float height = bImg.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page);
PDImageXObject img = LosslessFactory.createFromImage(document, bImg);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 0, 0);
contentStream.close();
in.close();
pdf = document;
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
} catch (Exception e) {
e.printStackTrace();
}
} else if (fileType.equalsIgnoreCase("txt")) {
JEditorPane jEditorPane = new JEditorPane(fileUrl);
jEditorPane.print(null, null, false, printService, null, false);
} else if (fileType.equalsIgnoreCase("pdf")) {
pdf = PDDocument.load(new URL(fileUrl).openStream());
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
}
} catch (Exception e) {
throw new PrintException("Printer exception", e);
}
return true;
}
I have String with Html format. My Html can contains any tags like image , video , ...
I can now handle image and text like this correctly :
I have a textView in my xml:
TextView textView = new TextView(DetailActivity.this);
textView.setText(Html.fromHtml(content, new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
try {
URI uri = new URI(source);
URL videoUrl = uri.toURL();
File tempFile = new File(videoUrl.getFile());
filename = tempFile.getName();
} catch (Exception e) {
}
Drawable drawable = null;
ContextWrapper cw1 = new ContextWrapper(DetailActivity.this);
File directory1 = cw1.getDir("multiImage", Context.MODE_PRIVATE);
final File myImageFile1 = new File(directory1, filename);
File f = new File(myImageFile1.getAbsolutePath());
Log.i("multiImage", filename);
final ImageView imageView = new ImageView(DetailActivity.this);
if (f.exists()) {
drawable = Drawable.createFromPath(myImageFile1.getAbsolutePath());
//drawable.setBounds(0, 0, drawable.getIntrinsicHeight(), drawable.getIntrinsicWidth());
int imgH = drawable.getIntrinsicHeight();
int imgW = drawable.getIntrinsicWidth();
int padding = 20;
int realWidth = ScreenW - (2 * padding);
int realHeight = imgH * realWidth / imgW;
drawable.setBounds(padding, 0, realWidth, realHeight);
} else {
Picasso.with(DetailActivity.this)
.load(source)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File outFile = new File(myImageFile1.getAbsolutePath());
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError() {
}
});
URL sourceURL;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
sourceURL = new URL(source);
URLConnection urlConnection = sourceURL.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bufferedInputStream =
new BufferedInputStream(inputStream);
Bitmap bm = BitmapFactory.decodeStream(bufferedInputStream);
// convert Bitmap to Drawable
drawable = new BitmapDrawable(getResources(), bm);
int imgH = drawable.getIntrinsicHeight();
int imgW = drawable.getIntrinsicWidth();
int padding = 20;
int realWidth = ScreenW - (2 * padding);
int realHeight = imgH * realWidth / imgW;
drawable.setBounds(padding, 0, realWidth, realHeight);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return drawable;
}
}, new UlTagHandler()));
But I can not show video using above code.
I want to split my string --> from the first until the video tag and then video tag at the end of video tag and the rest of string .
There was a problem with saving the graphics I received in the form of a picture in a folder on the computer. It seems to me that the problem is in the saving method in the picture, but I do not know how to fix the problem. I marked the problem area in the code (saveImage), I hope for your help)
//create Graph
XYSeriesCollection seriesCollection1 = new XYSeriesCollection(series1);
chart1 = ChartFactory.createXYLineChart("Зависимость скорости полета от t",
"Время, с", "Скорость полета, км/ч", seriesCollection1, PlotOrientation.VERTICAL, false, true, false);
chartPanel1 = new ChartPanel(chart1);
chartPanel1.setPreferredSize(new Dimension(1300, 480));
panel.add(chartPanel1);
//saving method in picture
public void saveImage(File file) {
Rectangle rec = chartPanel1.getBounds();
BufferedImage img = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
print(img.getGraphics()); // I think problem here.
try {
ImageIO.write(img, "png", file);
JOptionPane.showMessageDialog(null, "Данное изображение сохранено", "", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Ошибка сохранения", "", JOptionPane.ERROR_MESSAGE);
}
}
//listener
saveImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == saveImage) {
JFileChooser fc = new JFileChooser();
int op = fc.showSaveDialog(OpenFIle.this);
if (op == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4){
ext = filename.substring(len - 4, len);
}
if (ext.equals(".png")){
file = path + "\\" + filename;
}else {
file = path + "\\" + filename + ".png";
}
saveImage(new File(file));
}
}
}
});
}
The problem was solved in this way
public void saveImage(File file) {
Rectangle rec = chartPanel1.getBounds();
BufferedImage img = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
chartPanel1.paint(g);
try {
ImageIO.write(img, "png", file);
JOptionPane.showMessageDialog(null, "Данное изображение сохранено", "", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
}
}
I have a screen capture method that does half the job, it takes the screen shot but the images with PNG extention have transparent background and with JPEG it displays Black bakground. How can I capture the background (desktop wallpaper) ?
public void takeScreenshot() throws IOException {
date = new DateIAinnot();
view = ((Activity) context).getWindow().getDecorView().getRootView();
view.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
root = Environment.getExternalStorageDirectory().toString();
myDir = new File(root + "/Pictures");
myDir.mkdirs();
fname = date.getDate(2) + ".png";
fname = fname.replace(':', '_');
fname = fname.replace(' ', '-');
file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
openScreenshot(file);
} catch (Exception e) {
e.printStackTrace();
}
}