2015-01-05 1 views
1

Я работаю над кодом, который печатает квитанции на непрерывном рулоне бумаги, используя принтер квитанции. Квитанции похожи на то, что вы получаете, когда платите с помощью кредитной карты в магазине.Нежелательное дополнительное пустое пространство при печати на сплошном рулоне бумаги с использованием AirPrint

Я использую UIMarkupTextPrintFormatter, как вы можете видеть ниже в моем коде.

Но по какой-то причине я продолжаю получать пустое пространство как в середине, так и в конце напечатанного текста. (После печати последней строки принтер продолжает прокатывать еще несколько дюймов пустой бумаги!)

Я проверил свойство pageCount и он возвращает 2, поэтому, вероятно, именно здесь происходит дополнительное пустое пространство.

Я также включил диапазон страниц для отображения количества страниц (для отладки). Я не должен получать диапазон страниц на контроллере. Но я, и это предполагает, что мой контент превышает 2 страницы.

Не могли бы вы указать, где мой код не подходит? Каков правильный способ печати моего содержимого HTML на непрерывном рулоне бумаги?

Мой код отлично работает на симуляторе принтера. Я получаю точный результат, к которому я стремился. Никакого неожиданного пробела. Но он не работает на подлинном принтере для принтеров AirPrint!

Любое предложение очень ценится.

UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController]; 
if(!controller){ 
    DDLogInfo(@"Couldn't get shared UIPrintInteractionController!"); 
    return; 
} 

UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) { 
    if(!completed && error) 
     DDLogInfo(@"FAILED! due to error in domain %@ with error code %ld", error.domain, (long)error.code); 
}; 

controller.showsPageRange = YES; 
controller.showsPaperSelectionForLoadedPapers = YES; 

// Since the we're using a formatter, explicitly set the other properties to nil 
controller.printingItem = nil; 
controller.printingItems = nil; 
controller.printPageRenderer = nil; 


UIMarkupTextPrintFormatter *formatter = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:[self htmlPrintContent]]; 
formatter.startPage = 0; 
formatter.contentInsets = UIEdgeInsetsZero; 
controller.printFormatter = formatter; 

// Ask for a print job object and configure its settings to tailor the print request 
UIPrintInfo *info = [UIPrintInfo printInfo]; 

// B&W or color, normal quality output for mixed text, graphics, and images 
info.outputType = UIPrintInfoOutputGrayscale; 

// Select the job named this in the printer queue to cancel our print request. 
info.jobName = @"somejobname"; 

// Make sure we are printing in a portrait orientation. 
info.orientation = UIPrintInfoOrientationPortrait; 

// We don't need duplex printing so set it to none explicitly 
info.duplex = UIPrintInfoDuplexNone; 

// Instruct the printing concierge to use our custom print job settings. 
controller.printInfo = info; 


// Present the standard iOS Print Panel that allows you to pick the target Printer, number of pages, etc. 
[controller presentFromRect:self.printButton.frame inView:self.view animated:YES completionHandler:completionHandler]; 

ответ

1

Я в конечном итоге переход на UISimpleTextPrintFormatter вместо UIMarkupTextPrintFormatter.

Все форматирование выполняется с помощью NSAttributedString

Также реализована

- (CGFloat)printInteractionController:(UIPrintInteractionController *)printInteractionController cutLengthForPaper:(UIPrintPaper *)paper 

для того, чтобы определить высоту, необходимую для моего текста.

CGFloat printableWidth = paper.printableRect.size.width; 

CGRect attributedStringBoundingRect = [attributedPrintContent boundingRectWithSize:CGSizeMake(printableWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil]; 

/* Calculate the margins of the roll */ 
CGFloat lengthOfMargins = paper.paperSize.height - paper.printableRect.size.height; 

/* The cut length is the height of the text, plus margins, plus content insets */ 
CGFloat cutLength = attributedStringBoundingRect.size.height + lengthOfMargins + formatter.contentInsets.bottom + formatter.contentInsets.top; 

Надеется, что это помогает ...

0

я обнаружил, что мне нужно вычесть полей из печати ширины при вызове boundingRectWithSize:options:context:. Например:

func printInteractionController(_ printInteractionController: UIPrintInteractionController, cutLengthFor paper: UIPrintPaper) -> CGFloat { 
    let size = CGSize(width: paper.printableRect.width - margin * 2, height: 0) 

    let boundingRect = attributedText.boundingRect(with: size, options: [ 
     .usesLineFragmentOrigin, 
     .usesFontLeading 
    ], context: nil) 

    return boundingRect.height + margin * 2 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^