davbfr / dart_pdf Goto Github PK
View Code? Open in Web Editor NEWPdf creation module for dart/flutter
Home Page: https://pub.dev/packages/pdf
License: Apache License 2.0
Pdf creation module for dart/flutter
Home Page: https://pub.dev/packages/pdf
License: Apache License 2.0
HI David,
Could you please see my question in stackoverflow? Hope you can help.
https://stackoverflow.com/questions/53089690/flutter-capture-the-widget-to-image-and-then-create-pdf-file-to-printer
build: (pWidget.Context context) => <pWidget.Widget>[
pWidget.Header(level: 2, text: "Overall Attendance Report"),
pWidget.Table.fromTextArray(context: context, data: [
["Name", "Address", "Contact"],
dataList[0],
dataList[1],
]),
how can i iterate List<List> dynamically ?
I saw printscreen in the example.
I need to print a scrolling listview where some of the lines are longer than the screen size.
Does this plugin support that ?
Hi,
first of all: thanks for that great library. It's a breeze to work with it through it's awesome widget layer.
I was wondering, whether (and how) it would be possible to add a hyperlink to a PDF.
Thanks in advance.
I have a long description field. The user is given maxLines: 5.
But the entered text does not have line breaks, so would you have any suggestion as to how I could extract / calc the individual lines for rendering with drawString ?
Anyway, great library. Many thanks.
Wrap widget Source
Describe alternatives you've considered
Couldn't find any alternatives
This is a very ambitious issue.
There is no reason this can't work on desktop. The plugins can be replaced with windows and Mac equivalents and it should work.
I noticed that a Paragraph
(and other Widgets) have hardcoded text styles. Please make them configurable. Adding a style
parameter (and also textAlign
and margin
would be helpful. In addition, a way to define my own defaults would be great.
Because the current Theme
cannot be changed, this is my workaround I came up with. I'm sharing it in case somebody wants to do the same:
class MyTheme extends Theme {
MyTheme(PdfDocument document) : super(document);
TextStyle get paragraphStyle => TextStyle(
font: PdfFont.courier(document),
fontSize: 12,
lineSpacing: 5,
);
}
class DefaultTheme extends StatelessWidget {
final Theme theme;
final Widget child;
DefaultTheme({this.theme, this.child});
@override
Widget build(Context context) {
context.inherited[Theme] = theme;
return child;
}
}
Using context.inherited
feels be a bit hacky, but I couldn't use return child.build(context.inheritFrom(theme)
because Widget
has no build
method and because this would use MyTheme
as key, not Theme
, which would be required to use this.
BTW, if Parapgraph
has its own default in Theme
, Header
also should have a some kind of headerStyle
instead of using defaultTextStyle
.
PS: I really like the idea to use Flutter-compatible widgets for creating pages.
Thanks for your fine library, it is unique and helps a lot. Sadly I am not good enough to help the lib or even help myself, understanding that PDF encoding is very complicated, therefore I open this issue.
I want to print values with currency symbol, dollar and pound do work, no surprise somehow, but euro symbol drives me nuts.
I tested with Unicode branch and different fonts, loaded TTF fonts. I checked the euro symbol is where it should be in the fonts. Symbol Unicode | ₠
The character printed looks like a small < sign, no matter my fonts (arial, sans, mono, courier) . I am on a ubuntu 18.10.
Any ideas for a workaround for this kind of edge cases, somehow printing out symbols hard coded or in any other way, would be highly appreciated.
seems they changed some things about how things need to be laid out.
Gradle was going bananas !
Basically you just need to make the examples directory a proper Flutter project.
Just go into ./pdf && flutter create example
then from the example folder pubspec.yaml, reference your plugin using the ../ notation.
then just copy your example main.dart into it
EDIT:
here is an example: https://github.com/memspace/zefyr/blob/master/packages/zefyr/example/pubspec.yaml
I am creating a pdf in which I want a part of the text to be Bold. It can be done using rich text, but I guess support for rich text is not given in this plugin. Can you help me with that.
I tried to use multiple Text widgets but then the second Text widget goes to another line. Please tell me how to solve this.
Expected:
I want something like this.
What I get:
I am getting
something
like this
Works on Android but not iOS (both Simulators)
I have added use_frameworks! to PodFile.
On the iOS ipad simulator I get the following then app termnates:
flutter: build
*** First throw call stack:
(
0 CoreFoundation 0x0000000104b071e6 __exceptionPreprocess + 294
1 libobjc.A.dylib 0x000000010419c031 objc_exception_throw + 48
2 CoreFoundation 0x0000000104b88784 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x0000000104a895f8 forwarding + 760
4 CoreFoundation 0x0000000104a89278 _CF_forwarding_prep_0 + 120
5 Flutter 0x00000001023567ba __45-[FlutterMethodChannel setMethodCallHandler:]_block_invoke + 115
Lost connection to device.
6 Flutter 0x00000001023734ac _ZNK5shell21PlatformMessageRouter21HandlePlatformMessageEN3fml6RefPtrIN5blink15PlatformMessageEEE + 166
7 Flutter <…>
Hi, I'm trying to generate a PDF inside a flutter app, using a custom TrueType font, NotoSans.
This fails with NoSuchMethodError: The method 'replaceAll' was called on null.
, on line baseFont = "/" + font.fontName.replaceAll(" ", "");
. The offending code is here, it seems like font.fontName
is null for this particular font, not sure if this is a problem with the font file or the parsing. Maybe it should deal with a missing name more gracefully?
To reproduce:
NotoSans-Regular.ttf
var pdf = PDFDocument();
var page = PDFPage(pdf);
var bytes = await rootBundle.load('assets/NotoSans-Regular.ttf');
var font = PDFTTFFont(pdf, bytes);
Thanks for writing this library!
I have pdf with more page and I would like to write line separator from each other.
I just tried with PDFBorder but it doesn't work
How can I do this ?
When Trying to use it on my new AngularDart app, I get the error
The current Dart SDK version is 2.0.0.
Because sourcerer_web depends on pdf >=1.0.1 which requires SDK version >=1.8.0 <2.0.0, version solving failed.
Hi, i don't understand how i can print image loaded from Flutter assets.
That's my code, the only thing i get is:
Exception has occurred.
RangeError (index): Index out of range: index should be less than 15107: 15108
Future<PDFDocument> _generateDocument() async{
final pdf = new PDFDocument(deflate: zlib.encode);
final page = new PDFPage(pdf, pageFormat: PDFPageFormat.A4);
final g = page.getGraphics();
final font = new PDFFont(pdf);
final top = page.pageFormat.height;
ByteData data = await rootBundle.load('assets/images/back.png');
PDFImage image = new PDFImage(
pdf,
image: data.buffer.asUint8List(),
width: 86,
height: 80);
g.drawImage(image, 100.0, 100.0, 86.0);
g.setColor(new PDFColor(0.3, 0.3, 0.3));
g.drawString(font, 12.0, "Qui verranno i dati del PDF!", 10.0 * PDFPageFormat.MM,
top - 20.0 * PDFPageFormat.MM);
g.drawString(font, 12.0, "Qui verranno i dati del PDF!", 10.0 * PDFPageFormat.MM,
top - 30.0 * PDFPageFormat.MM);
g.drawString(font, 12.0, "Qui verranno i dati del PDF!", 10.0 * PDFPageFormat.MM,
top - 40.0 * PDFPageFormat.MM);
g.drawString(font, 12.0, "Qui verranno i dati del PDF!", 10.0 * PDFPageFormat.MM,
top - 50.0 * PDFPageFormat.MM);
return pdf;
}
void _printPdf() async{
final pdf = await _generateDocument();
print(pdf);
Printing.printPdf(document: pdf);
}
The image widget seems to be broken and just doesn't work with any uint image.
Thanks to Time Machine, I'm able to turn the clock back to before 'flutter upgrade'.
Is there a plan to get pdf and printing packages to work with the latest flutter 1.2.1, which depends on the newer AndroidX ?
Right now I'm using 👍
pdf: ^1.3.2
printing: ^1.3.2
Right now, it seems like the whole font is embedded inside each PDF. Is there an option to only include the characters actually used?
"setOrientation" method does not change the display of the page. the irientation is always portrait orientation mode. How to change orientation of a page (Portrait, Landscape).
Describe the bug
I have been trying for days now and i cannot seem to add an image with my pdf document. When i run the function that creates the pdf, the text shows in the pdf perfectly, but the image shows as a black square.
To Reproduce
Steps to reproduce the behavior:
Enter code below ::
ByteData bytes = await rootBundle.load('assets/images/1.jpg');
var codec = await instantiateImageCodec ( bytes.buffer.asUint8List() );
var frame = await codec.getNextFrame();
var imageBytes = await frame.image.toByteData();
PdfImage image = new PdfImage(pdf.document, image: imageBytes.buffer.asUint8List(),
width: 20, height: 20);
Am i doing something wrong here?
Expected behavior
Pdf document would include the jpg or png image.
Smartphone (please complete the following information):
Additional context
cant use the printing plugin along with firebase messaging. it doesn't compile.
According to Dart's style guidelines, acronyms and abbreviations longer than two letters should be treated as words
// GOOD
PdfDocument
PdfTtfFont
// BAD
PDFDocument
PDFTTFFont
I have to admit I seem to be a bit unlucky. Following #41 I'm building with the following quick example:
Widget build(BuildContext ctx) {
return Center(
child: FlatButton(
child: Text("Build"),
onPressed: () async {
Printing.layoutPdf(onLayout: (_) {
return generatePDF(state);
});
// Directory appDocDir = await getApplicationDocumentsDirectory();
// String appDocPath = appDocDir.path;
// File file = File(appDocPath + "/test.pdf");
// await file.writeAsBytes(pdf);
},
),
);
}
where generatePDF(state)
is your example PDF code. (This results in a perfectly fine PDF when saved to a file using the commented out code above instead of running Printing.)
However, when run in flutter the above generates:
Tried calling: invokeMethod<void>("printPdf", _LinkedHashMap len:1)
Found: invokeMethod(String, [dynamic]) => Future<dynamic>
#0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
#1 Printing.layoutPdf
../…/src/printing.dart:52
<asynchronous suspension>
#2 PDFWidget.build.<anonymous closure>
package:RWYRA/…/pdf/pdf.dart:23
<asynchronous suspension>
#3 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:507
#4 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:562
#5 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:102
#6 TapGestureRecognizer._checkUp (package:flutter/<…>
Similarly, if I try just Printing.sharePdf(bytes: generatePDF(state));
this gives
Tried calling: invokeMethod<void>("sharePdf", _LinkedHashMap len:6)
Found: invokeMethod(String, [dynamic]) => Future<dynamic>
#0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
#1 Printing.sharePdf
../…/src/printing.dart:89
<asynchronous suspension>
#2 PDFWidget.build.<anonymous closure>
package:RWYRA/…/pdf/pdf.dart:23
<asynchronous suspension>
#3 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:507
#4 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:562
#5 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:102
#6 TapGestureRecognizer._checkUp (package:flutter/s<…>
Am I missing something obvious?
My questions:
Dave, great looking library.
My app draws a lot of canvas.
I notice the Microsoft Graphics doc has a drawEllipsis(), but not drawArc().
Are you planning to add ?
Or is there any current way to produce arcs and rounded rects ?
Would I need to workaround by covering an ellipsis with rects to achieve an arc ? etc ?
Thanks anyway,
Ian
The return type 'Container' isn't a 'Widget', as defined by anonymous closure
Dave, your sample works.
My pdf generates into a file ok, but when I try the print option, the preview is blank and I get these error messages: (only tried on the iphone X simulator)
flutter: Print ...
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x604000290db0 UIView:0x7ff052f6dbe0.width == UILabel:0x7ff052f735a0'Page 1'.width + 28 (active)>",
"<NSLayoutConstraint:0x604000291ad0 H:[UIImageView:0x7ff052f73880]-(3)-UILabel:0x7ff052f735a0'Page 1' (active)>",
"<NSLayoutConstraint:0x604000288980 UIImageView:0x7ff052f73880.width == 22 (active)>",
"<NSLayoutConstraint:0x60400028b720 H:|-(0)-UIImageView:0x7ff052f73880 (active, names: '|':UIView:0x7ff052f6dbe0 )>",
"<NSLayoutConstraint:0x604000285140 UILabel:0x7ff052f735a0'Page 1'.right == UIView:0x7ff052f6dbe0.right (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x604000291ad0 H:[UIImageView:0x7ff052f73880]-(3)-UILabel:0x7ff052f735a0'Page 1' (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
can we set something like circle progress indicator to show percentage in pdf?
How about the other way around, opening the PDF? Even the plain text alone would be great for a start!
Hi,
When I install Package showing some error.
Running "flutter packages get" in pdf_test...
Because every version of flutter_test from sdk depends on vector_math 2.0.6 and pdf_test depends on vector_math ^2.0.7, flutter_test from sdk is forbidden.
So, because pdf_test depends on flutter_test any from sdk, version solving failed.
pub get failed (1)
pubspec.yaml
dependencies:
ttf_parser: ^1.0.0
meta: ^1.1.5
vector_math: ^2.0.7
pdf: ^1.0.0
flutter:
sdk: flutter
I need to print receipts over wifi or bluetooth. Thank you!
https://www.epson.co.in/For-Work/Printers/POS-Printers/Epson-TM-P20-2%22-Mobile-Thermal-POS-Receipt-Printer/p/C31CE14061
Dave,
I have hit a brick wall with this.
I was hoping to be able to add flutter image assets to my pdf.
Is the only way to achieve this via the RenderRepaintBoundary.toImage() ?
Cheers in hope there's a more straightforward way...
Ian
Thank you.
Hello everyone could you please tell me does it support with Thermal Printer? why I can't find bluetooth thermal printer during searching. Thanks
At the moment, the table is a bit tricky to use with strings because it breaks if a cell overflows. That is, the following example:
List<int> testPDF() {
final Document pdf = Document(deflate: zlib.encode);
pdf.addPage(
MultiPage(
pageFormat:
PdfPageFormat.a4.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),
build: (Context context) => <Widget>[
Header(level: 0, text: 'Table Test'),
Table.fromTextArray(context: context, data: <List<String>>[
<String>['Field', 'A', 'B', 'C'],
<String>[
'Foo',
'This is a quite long field which may require breaking',
'This is a quite long field which may require breaking',
'This is a quite long field which may require breaking',
],
]),
],
),
);
return pdf.document.save();
}
fails to render with
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'toDouble' was called on null.
Receiver: null
Tried calling: toDouble()
#0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
#1 double.+ (dart:core/runtime/libdouble.dart:17:23)
#2 RichText.layout ../…/widgets/text.dart:233
#3 Align.layout ../…/widgets/basic.dart:241
#4 Padding.layout ../…/widgets/basic.dart:75
#5 StatelessWidget.layout ../…/widgets/widget.dart:99
#6 Table.layout ../…/widgets/table.dart:228
#7 MultiPage.generate (file:///Users/jb/sdk/flutter/.pub-cache/hosted/pub<…>
I have been looking at allowing text wrap, and from your suggestion have been attempting to use stringBounds().
This issue I have is that the both glyphBounds() and glyphAdvance() return hard coded values, therefore it is impossible to accurately use stringBounds() to determine the length of a string.
double glyphAdvance(int charCode) {
return 0.454;
}
PDFRect glyphBounds(int charCode) {
return const PDFRect(0.0, 0.0, 0.4, 1.0);
}
for example:
String foo = "WW";
String bar = "ii";
stringBounds() says these are the same length, but they are not a W is wider that i.
Is there any other way of accurately determining the wide of a string, or is it that this is currently not possible?
Hello,
I have encountered a problem with drawString method and utf8 characters. After calling for example
g.drawString('E.B. Lukáča');
, method throws exception. After debugging, it looks like there is support only for Latin1 which does not contain all characters I need. In this example it is letter 'č'. Is it possible to add UTF-8 support?
Thanks in advance.
hello when i use the code from the example on ios it gives me this error:
FileSystemException: Cannot open file, path = 'example.pdf' (OS Error: Operation not permitted, errno = 1)
And on android i have this permissions:
WRITE_EXTERNAL_STORAGE
READ_EXTERNAL_STORAGE
giving similar error:
FileSystemException: Cannot open file, path = 'example.pdf' (OS Error: Read-only file system, errno = 30)
i dont know if its a bug or i am missing a permission.
Hi, thanks for the plugin but i can't make it work. When tapping on the print button i get this error
"Exception has occurred. PlatformException(error, java.util.ArrayList cannot be cast to byte[], null)".
Please, how can i solve this?
I'm currently developing an iOS Flutter app who need background printing.
I look at this plugin and starting a fork to implement the iOS UIPrintInteractionController
printToPrinter
method allowing to print without showing the native UI.
I simply made a copy of printPdf
method (in PrintingPlugin.m
) and replacing
[controller presentAnimated:YES completionHandler:completionHandler];
with
NSURL* printerURL = [NSURL URLWithString:printerID];
UIPrinter* printer = [UIPrinter printerWithURL:printerURL];
[controller printToPrinter:printer completionHandler:completionHandler];
Having printerID
a NSString
passed as parameter.
But when I call this method, a popup show up saying:
Printing to "my-printer.local."
Contacting printer...
And the popups "Cancel" button doesn't work...
Anyone seeing what's happens?
Here is my fork with PrintingPlugin.m
and printing/example
modified: https://github.com/TristanPct/dart_pdf
Here is the StackOverflow issue referencing the same issue: https://stackoverflow.com/questions/54810047/ios-uiprintinteractioncontroller-printtoprinter-contacting-printer
How to have the size in pixel of a text linked a font.
In java with PDFBOX, I have the method GetStringWidth
Example:
PDFont mDefaultFont = PDType1Font.HELVETICA;
float textWidth = (mDefaultFont.getStringWidth (lText) / 1000) * mFontSize;
Which method to use with pdf dart
I can't seem to get this to build for iOS. With flutter 1.0, having just added printing: ^1.3.3
to the pubspec,
$ flutter build ios
Building ... for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: ...
Running pod install... 1.5s
Starting Xcode build...
Xcode build done. 8.8s
Failed to build iOS app
Error output from Xcode build:
↳
** BUILD FAILED **
Xcode's output:
↳
/Users/jb/sdk/flutter/.pub-cache/hosted/pub.dartlang.org/printing-1.3.3/ios/Classes/PrintingPlugin.m:18:9: fatal
error: 'printing/printing-Swift.h' file not found
#import <printing/printing-Swift.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
Encountered error while building for device.
I also set SWIFT_VERSION=4.2
in the environment as otherwise pod install could not complete. I don't think the above is related, though.
Any advice?
Describe the bug
I'm having some trouble adding my Uint8List image into my Document, the PdfImage constructor expects a PdfDocument value but my PDF is a Document not a PdfDocument
To Reproduce
Code snippet to reproduce the behavior:
Document pdf;
Uint8List customerImageBytes;
Image(PdfImage(pdf, image: customerImageBytes, width: 100, height: 20)));
Expected behavior
I need a way to be able to add the Image to the Document as I have constructed the whole document using the Document.addPage method I need to find a way to add an image inside of the addPage build constructor:
pdf = Document().addPage(Page(
pageFormat: PdfPageFormat.a4,
build: (Context context) {
```
return Container(decoration: BoxDecoration(border: BoxBorder(width: 2.0, top: true, right: true, bottom: true, left: true)), child: Container(color: PdfColors.grey300, child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
Container(width: 300.0, color: PdfColors.black, child: Text('MAINTENANCE/SERVICE CHECK LIST', textAlign: TextAlign.center ,style: TextStyle(font: Font(), color: PdfColor(255, 255, 255)))),
Container(height: 10.0),`
Hello, if i try to add images works but it takes 2 minutes to generate the pdf i dont know if exists a way to do it faster.
im taking the image with this code (image picker library):
File _image;
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
}
then adding it to the pdf like this:
Image img = decodeImage(_image.readAsBytesSync());
PDFImage image = new PDFImage(
pdf,
image: img.data.buffer.asUint8List(),
width: img.width,
height: img.height);
g.drawImage(image, 100.0, top - 150.0, 80.0, 100.0);
It would be nice to be able to set a (default) filename for saving instead of the "document##############.pdf" it currently does when you share.
I couldn't see anything that would do this, but if I missed it I'd be happy to find that out =). I tried setting the PDFInfo.title and that didn't do it.
I would love to use this package in a web app to dynamically create a PDF and download it right from the browser. This is not possible currently due to dart:io not being available in the browser. Would it be possible to replace dart:io with the archive
package which also has a ZLib encoder? The resulting code would be able to be run on the web, Flutter and VM.
https://pub.dartlang.org/packages/archive
Also ByteBuffer
from dart_types instead of BytesBuilder
from dart:io?
I got this error:
E/flutter ( 7635): [ERROR:flutter/shell/common/shell.cc(188)] Dart Error: Unhandled exception:
E/flutter ( 7635): RangeError (index): Invalid value: Not in range 0..1023, inclusive: 1040
E/flutter ( 7635): #0 List.[] (dart:core/runtime/libgrowable_array.dart:145:60)
E/flutter ( 7635): #1 PDFTTFFont.glyphAdvance (file:///home/redsolver/flutter/.pub-cache/hosted/pub.dartlang.org/pdf-1.0.7/lib/src/ttffont.dart:61:30)
E/flutter ( 7635): #2 new PDFTTFFont (file:///home/redsolver/flutter/.pub-cache/hosted/pub.dartlang.org/pdf-1.0.7/lib/src/ttffont.dart:45:19)
E/flutter ( 7635): #3 _PrintState._generateDocument (package:taggle/print.dart:175:27)
E/flutter ( 7635): <asynchronous suspension>
with this code
final pdf = new PDFDocument(
deflate: zlib.encode,
);
var ttf = await rootBundle.load("assets/roboto.ttf");
PDFTTFFont font = new PDFTTFFont(pdf, ttf); // Error here
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.