Ok, I thinnk it's more like "where I can find It" than a real question.
I'm using the zxing to build a QR Code engine for my system, it's work really cool, but I need make some customizations.
At https://www.qrcode-monkey.com/ I found a QR Code builder with some templates that can be read for any qr code reader.
The Colors can be changed with MatrixToImageConfig class, but I didn't found a way to change the shape.
Anyone knows a library that do this?!
This class is for change the qr code color.
public class QRCodeServiceImpl {
public static final int ON_COLOR = 0xFFFF9F37;
public static final int OFF_COLOR = 0xFF6638B6;
public byte[] buildQRCode(String data) throws WriterException, IOException {
Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hintMap.put(EncodeHintType.MARGIN, 1);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, 512, 512, hintMap);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream, getMatrixConfig());
byte[] fileData = pngOutputStream.toByteArray();
return fileData;
}
private MatrixToImageConfig getMatrixConfig() {
MatrixToImageConfig config = new MatrixToImageConfig(ON_COLOR, OFF_COLOR);
return config;
}
}
Related
So i have a method tha takes and user Id and a multipartFile and uploads it to aws and im trying to test it but i get and error java.lang.IllegalArgumentException: Not enough variable values available to expand
this is the method to upload the file
public void uploadUserProfileImage(#PathVariable("userProfileId")UUID userProfileId ,
#RequestParam("file")MultipartFile file){
userProfileService.uploadUserProfileImage(userProfileId,file);
}
and this is the test i came up with, im trying to learn how to test my methods.
#Test
void uploadUserProfileImage() throws Exception {
BufferedImage img;
img = ImageIO.read(new File("src/main/java/images/bane.png"));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(img, "file", byteArrayOutputStream);
byte[] byteArryaImg = byteArrayOutputStream.toByteArray();
//given
MockMultipartFile file = new MockMultipartFile("file",
"file",
MediaType.IMAGE_PNG_VALUE,
byteArryaImg);
UserProfileModel user = new UserProfileModel(UUID.randomUUID(), "luad", "ada");
String userProfileId = user.getUserProfileId().toString();
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(multipart("/{userProfileId}/image/upload")
.file(file)
.accept(MediaType.IMAGE_PNG))
.andExpect(status()
.isOk());
}
I suppose that you may use such as following;
MockMultipartFile mockMultipartFile = new MockMultipartFile("image-name", "mock-file.png", "image/jpeg", "image".getBytes());
MockHttpServletRequestBuilder mockRequest = fileUpload("/{userProfileId}/image/upload").file(mockMultipartFile)
you need to import fileUpluad method from;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
then, just perform such as;
mockMvc.perform(mockRequest).andExpect(status().isOk());
I am visualizing some data with vaadin-charts:3.2.0, and I am trying to export a SVG out from the chart. I get some results but it is not satisfying. I can only share the screenshosts instead of the SVG itself. I also had to pixelate the labels to mask private data.
Original vaadin-charts seen on screen:
Exported SVG:
One problem is that the labels overflow the svg boundaries. And the chart drawings also overflow the boundaries making it seem like an incomplete drawing. Any idea what is wrong with this structure?
public class SvgStreamResource extends StreamResource {
public SvgStreamResource(String svgText, String filename) {
super(new StreamSource() {
#Override
public InputStream getStream() {
InputStream s = new BufferedInputStream( new ReaderInputStream(new StringReader(svgText)));
return s;
}
}, filename + ".svg");
}
#Override
public String getMIMEType() {
return "image/svg+xml";
}
}
Within a component:
Button exportButton = createExportButton("SVG", createSVGStreamSource(conf));
private SvgStreamResource createSVGStreamSource(Configuration conf) {
String svg = SVGGenerator.getInstance().generate(conf);
return new SvgStreamResource(svg, fileBaseName);
}
private Button createExportButton(String caption, SvgStreamResource svgStreamResource) {
Button b = new Button(caption);
FileDownloader downloader = new FileDownloader(svgStreamResource);
downloader.extend(b);
return b;
}
I created a pdf using the following example:
https://developers.itextpdf.com/examples/actions-and-annotations/clone-creating-and-adding-annotations#2260-addstamp.java
#Category(SampleTest.class)
public class AddStamp extends GenericTest {
public static final String DEST = "./target/test/resources/sandbox/annotations/add_stamp.pdf";
public static final String IMG = "./src/test/resources/img/itext.png";
public static final String SRC = "./src/test/resources/pdfs/hello.pdf";
public static void main(String[] args) throws Exception {
File file = new File(DEST);
file.getParentFile().mkdirs();
new AddStamp().manipulatePdf(DEST);
}
#Override
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
ImageData img = ImageDataFactory.create(IMG);
float w = img.getWidth();
float h = img.getHeight();
Rectangle location = new Rectangle(36, 770 - h, w, h);
PdfStampAnnotation stamp = new PdfStampAnnotation(location)
.setStampName(new PdfName("ITEXT"));
PdfFormXObject xObj = new PdfFormXObject(new Rectangle(w, h));
PdfCanvas canvas = new PdfCanvas(xObj, pdfDoc);
canvas.addImage(img, 0, 0, false);
stamp.setNormalAppearance(xObj.getPdfObject());
stamp.setFlags(PdfAnnotation.PRINT);
pdfDoc.getFirstPage().addAnnotation(stamp);
pdfDoc.close();
}
}
The pdf is properly created and contains the stamp annotation
I can get the annotation using:
...
PdfStampAnnotation s = (PdfStampAnnotation) pdfDoc.getFirstPage().getAnnotations().get(0);
s.?????
How can I get back the image (itext.png) of the stamp (eg: byte[]) ?
I'm really new to itext and after hours of research I'm stuck at this point...
First of all, you won't get the original image back. PDF support only very few bitmap image formats as they are: JPEG, JPEG2000, certain fax formats, but definitively not PNG. PNGs are converted into the PDF internal bitmap format, and upon extraction can best be converted back to a PNG.
Furthermore, the reason why there is no simple getImage method in the PdfStampAnnotation class is that the appearance of a stamp may be constructed like the contents of a regular page, it may contain text, it may contain vector graphics, it may contain bitmap images, it may contain an arbitrary mixture of those elements. Thus, all you can retrieve from an annotation is its appearance.
If you are sure an annotation contains only an image (or you at least are not interested in anything but the image), you can extract that image using the iText parser framework, e.g. like this:
Map<byte[], String> extractAnnotationImages(PdfStream xObject) {
final Map<byte[], String> result = new HashMap<>();
IEventListener renderListener = new IEventListener() {
#Override
public Set<EventType> getSupportedEvents() {
return Collections.singleton(RENDER_IMAGE);
}
#Override
public void eventOccurred(IEventData data, EventType type) {
if (data instanceof ImageRenderInfo) {
ImageRenderInfo imageRenderInfo = (ImageRenderInfo) data;
byte[] bytes = imageRenderInfo.getImage().getImageBytes();
String extension = imageRenderInfo.getImage().identifyImageFileExtension();
result.put(bytes, extension);
}
}
};
PdfCanvasProcessor processor = new PdfCanvasProcessor(renderListener, Collections.emptyMap());
processor.processContent(xObject.getBytes(), new PdfResources(xObject.getAsDictionary(PdfName.Resources)));
return result;
}
(ExtractAnnotationImage method)
which returns a mapping from image byte arrays to file extension to use.
I used it in this helper method:
void saveAnnotationImages(PdfDocument pdfDocument, String prefix) throws IOException {
for (int pageNumber = 1; pageNumber <= pdfDocument.getNumberOfPages(); pageNumber++) {
PdfPage page = pdfDocument.getPage(pageNumber);
int index = 0;
for (PdfAnnotation annotation : page.getAnnotations()) {
PdfDictionary normal = annotation.getAppearanceObject(PdfName.N);
if (normal instanceof PdfStream) {
Map<byte[], String> images = extractAnnotationImages((PdfStream)normal);
for (Map.Entry<byte[], String> entry : images.entrySet()) {
Files.write(new File(String.format("%s-%s-%s.%s", prefix, pageNumber, index++, entry.getValue())).toPath(), entry.getKey());
}
}
}
}
}
(ExtractAnnotationImage helper method)
to extract all images from annotations from the output of the iText example AddStamp you reference and got one image:
By the way, you'll recognize here that transparency is missing. Transparency in the PDF is modeled via a second image, a mask image, which effectively represents something like an alpha channel. One can retrieve this mask from the ImageRenderInfo.getImage() object.
I am using CKEditor WYSWIG as my text editor on my site.
When User paste an image on the editor it is sent in post as <img src="data:image/png;base64,iVBORw0KGgoAAAANsd..." />
I would like to get this base64 string, save it in database and then create endpoint like /image/{id} which will show this image so in post I would not have to put whole base64 string in image source but just url like shown above.
this is how I save the base64 as byte[]:
#RequestMapping(value = {"/main/createpost"}, method = RequestMethod.POST)
public String postPost(Model model, Principal principal,#RequestParam(name="editor-content") String postPayload) throws IOException {
postPayload = checkAndSavePhotos(postPayload);
model.addAttribute("editor",postPayload);
return "createpost";
}
checkAndSavePhotos is checking if editor contains any images and if so it stores it in database:
private String checkAndSavePhotos(String postPayload) throws IOException {
int i =1;
Pattern pattern = Pattern.compile(".*<img src=\".*;base64,(.*?)\".*/>");
Matcher matcher = pattern.matcher(postPayload);
while (matcher.find()) {
PostPhoto postPhoto = new PostPhoto();
byte[] bytes = Base64.getDecoder().decode(matcher.group(i).getBytes());
MultipartFile mf =null;
try {
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(bytes));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "png", baos);
baos.flush();
mf = new MockMultipartFile("test", baos.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
postPhoto.setContent(mf.getBytes());
postPhoto = postPhotoService.save(postPhoto);
}
return null;
}
I have made it this way because on my other form with <input type='file' /> when I was using FileBucket it was enough for me to show fileBucket.getFile().getBytes(); in order to show image. I was trying to create MultipartFile from byte[] and made it the same way.
My Endpoint to show image:
#RequestMapping(value = "/main/postphoto/{imageId}")
#ResponseBody
public byte[] getImage(#PathVariable Long imageId) throws IOException {
PostPhoto image = postPhotoService.findById(imageId);
return image.getContent();
}
Now when I am looking at database content column looks like:
\x89504e470d0a1a0a0000000d49484452000000280000002808060000008cfeb86d0000033f4944415478daed9(...)
while file from filebucket
\377\330\377\341\000\030Exif\000\000II*\000\010\000\000\000\000\000\000\000\000\000\000\000\377\354\000\021Ducky\000\001\000\004\000\000\000A\000\000\377\341\003ohttp://ns.adobe.com/xap/1.0/\000<?xpacket begin="\357\273\277" id="W5M0MpCehiHzreSzNTczkc9d"?> (...)
Can anyone give me a hint how to made it works?
It looks like it was a stupid mistake.
My database column content was type of text so I was storing byte[] as a text, so it's not wierd that the file was not decoded correctly by browser.
Changing database column type to bytea solved problem.
I am writing a program in Java (I am using Ubuntu). I am using Jodconverter to convert the document to PDF. I have to convert the document to landscape mode but I have read that Jodconverter doesn't support orientation changes. I also tried with OpenOffice API but I am facing the same issue.
Is there any Java library that does conversion to landscape?
From a similar question regarding using Jodconverter with an Open Office document:
http://groups.google.com/group/jodconverter/browse_thread/thread/dc96df64c7d60ada/c1692fee92513b7a
Short answer: you can't. The page orientation is a property of the
document (menu Format > Page in Calc), not a PDF export option. So it
should be set already in the XLS document.
Export to PDF and then use a PDF library like PDFbox to rotate the pages by 90 degrees.
Try PDPage.setRotation(int) on all pages (PDDocument.getDocumentCatalog().getAllPages()).
I have found the solution. I have converted document to landscape pdf using open office API for java. Here is the code for the same.
System.out.println("starting...");
String oooExeFolder = "/usr/lib/openoffice/program";
XComponentContext xContext = BootstrapSocketConnector.bootstrap(oooExeFolder);
XMultiComponentFactory xMCF = xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
XComponentLoader xCLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, oDesktop);
System.out.println("loading ");
PropertyValue[] printerDesc = new PropertyValue[1];
printerDesc[0] = new PropertyValue();
printerDesc[0].Name = "PaperOrientation";
printerDesc[0].Value = PaperOrientation.LANDSCAPE;
// Create a document
XComponent document = xCLoader.loadComponentFromURL(loadUrl, "_blank", 0, printerDesc);
// Following property will convert doc into requested orientation.
XPrintable xPrintable = (XPrintable) UnoRuntime.queryInterface(XPrintable.class, document);
xPrintable.setPrinter(printerDesc);
PropertyValue[] conversionProperties = new PropertyValue[3];
conversionProperties[1] = new PropertyValue();
conversionProperties[1].Name = "FilterName";
conversionProperties[1].Value = "writer_pdf_Export";//
conversionProperties[0] = new PropertyValue();
conversionProperties[0].Name = "Overwrite ";
conversionProperties[0].Value = new Boolean(true);
System.out.println("closing");
XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
xstorable.storeToURL(storeUrl, conversionProperties);
System.out.println("closing");
XCloseable xcloseable = (XCloseable) UnoRuntime.queryInterface(XCloseable.class, document);
xcloseable.close(false);
Try overriding OfficeDocumentConverter
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager) {
private Map<String, Object> createDefaultLoadProperties() {
Map<String, Object> loadProperties = new HashMap<String, Object>();
loadProperties.put("Hidden", true);
loadProperties.put("ReadOnly", true);
loadProperties.put("UpdateDocMode", UpdateDocMode.QUIET_UPDATE);
return loadProperties;
}
#Override
public void convert(File inputFile, File outputFile, DocumentFormat outputFormat) throws OfficeException {
String inputExtension = FilenameUtils.getExtension(inputFile.getName());
DocumentFormat inputFormat = getFormatRegistry().getFormatByExtension(inputExtension);
inputFormat.setLoadProperties(Collections.singletonMap("PaperOrientation", PaperOrientation.LANDSCAPE));
StandardConversionTask conversionTask = new StandardConversionTask(inputFile, outputFile, outputFormat) {
#Override
protected void modifyDocument(XComponent document) throws OfficeException {
PropertyValue[] printerDesc = OfficeUtils.toUnoProperties(Collections.singletonMap("PaperOrientation", PaperOrientation.LANDSCAPE));
XPrintable xPrintable = cast(XPrintable.class, document);
try {
xPrintable.setPrinter(printerDesc);
} catch (com.sun.star.lang.IllegalArgumentException e) {
logger.error(e.getMessage());
}
super.modifyDocument(document);
}
};
conversionTask.setDefaultLoadProperties(createDefaultLoadProperties());
conversionTask.setInputFormat(inputFormat);
officeManager.execute(conversionTask);
}
};